0
0
Wordpressframework~5 mins

Why custom queries retrieve specific data in Wordpress

Choose your learning style9 modes available
Introduction

Custom queries help you get exactly the posts or data you want from WordPress. They let you pick specific items instead of all content.

You want to show only posts from a certain category on a page.
You need to display posts written by a specific author.
You want to list posts published within a certain date range.
You want to get posts with a specific custom field value.
You want to limit the number of posts shown on a page.
Syntax
Wordpress
<?php
$args = array(
    'key' => 'value',
    // other query parameters
);
$query = new WP_Query($args);
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        // display post data
    }
    wp_reset_postdata();
}
?>

The $args array sets rules for which posts to get.

Always use wp_reset_postdata() after custom queries to restore original data.

Examples
Gets posts only from the 'news' category.
Wordpress
<?php
$args = array('category_name' => 'news');
$query = new WP_Query($args);
Gets posts written by the author with ID 5.
Wordpress
<?php
$args = array('author' => 5);
$query = new WP_Query($args);
Limits the query to 3 posts only.
Wordpress
<?php
$args = array('posts_per_page' => 3);
$query = new WP_Query($args);
Gets posts where the custom field 'color' is 'blue'.
Wordpress
<?php
$args = array('meta_key' => 'color', 'meta_value' => 'blue');
$query = new WP_Query($args);
Sample Program

This code gets the latest 2 posts from the 'news' category and prints their titles. It shows how custom queries retrieve specific data by setting rules.

Wordpress
<?php
/* Template to show posts from category 'news' */
$args = array('category_name' => 'news', 'posts_per_page' => 2);
$query = new WP_Query($args);
echo "Posts in 'news' category:\n";
if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        echo get_the_title() . "\n";
    }
} else {
    echo "No posts found.\n";
}
wp_reset_postdata();
?>
OutputSuccess
Important Notes

Custom queries run slower if you ask for many posts or complex filters.

Always reset post data after custom queries to avoid conflicts with main queries.

Use custom queries when you want to show filtered or limited posts, not for all content.

Summary

Custom queries let you pick exactly which posts to get from WordPress.

You set rules in an array to filter posts by category, author, date, or custom fields.

Always reset post data after running a custom query to keep your site working well.