0
0
Wordpressframework~5 mins

WP_Query class in Wordpress

Choose your learning style9 modes available
Introduction

The WP_Query class helps you get posts or content from your WordPress site easily. It lets you ask for specific posts based on rules you set.

You want to show a list of recent blog posts on your homepage.
You need to display posts from a specific category or tag.
You want to create a custom page showing posts by a certain author.
You want to filter posts by date or custom fields.
You want to build a custom archive or search results page.
Syntax
Wordpress
$query = new WP_Query( array( 'key' => 'value', 'key2' => 'value2' ) );

if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
        $query->the_post();
        // Your code to display the post
    }
    wp_reset_postdata();
}

The array inside WP_Query sets the rules for which posts to get.

Always use wp_reset_postdata() after your loop to restore original post data.

Examples
Get the latest 5 posts.
Wordpress
$query = new WP_Query( array( 'posts_per_page' => 5 ) );
Get posts from the category named 'news'.
Wordpress
$query = new WP_Query( array( 'category_name' => 'news' ) );
Get posts written by the author with ID 3.
Wordpress
$query = new WP_Query( array( 'author' => 3 ) );
Get posts where the custom field 'color' is 'blue'.
Wordpress
$query = new WP_Query( array( 'meta_key' => 'color', 'meta_value' => 'blue' ) );
Sample Program

This code gets the 3 newest posts from the 'news' category and prints their titles line by line.

Wordpress
<?php
// Create a new query to get 3 latest posts from category 'news'
$query = new WP_Query( array( 'posts_per_page' => 3, 'category_name' => 'news' ) );

if ( $query->have_posts() ) {
    echo "Latest news posts:\n";
    while ( $query->have_posts() ) {
        $query->the_post();
        echo get_the_title() . "\n";
    }
    wp_reset_postdata();
} else {
    echo "No posts found.";
}
?>
OutputSuccess
Important Notes

WP_Query does not change the main query unless you replace it; it creates a separate query.

Use have_posts() and the_post() to loop through results safely.

Remember to reset post data with wp_reset_postdata() after your custom loop.

Summary

WP_Query helps you fetch posts with custom rules.

Use it to show posts by category, author, date, or custom fields.

Always loop with have_posts() and reset after with wp_reset_postdata().