When you need to show a custom list of posts, such as the five latest news posts or all books by one author, WordPress gives you WP_Query. It is a PHP class that fetches posts from the database based on the conditions you set.
It is one of the most used tools in theme and plugin development. In this article, we will see what it does and how to use it.
Why Use WP_Query?
WordPress already runs a main query on every page to decide which posts to show. WP_Query lets you run your own extra queries alongside it. You simply describe what you want, and WordPress builds the database query for you, so you never write SQL.
It is just like handing a shopping list to a helper. You write "five posts, news category, newest first," and you get exactly that back.
How to Use WP_Query
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 5,
'category_name' => 'news',
) );
while ( $query->have_posts() ) {
$query->the_post();
the_title( '<h3>', '</h3>' );
}
wp_reset_postdata();
Here, post_type picks the content type, posts_per_page sets how many posts to fetch and category_name takes the category slug. You can also filter by tag, author, date or custom fields, and sort results with orderby and order.
Related posts are a common use of it, and we have ready code to display related posts by category in WordPress.
Mistakes to Avoid With WP_Query
- Always call
wp_reset_postdata()after your custom loop, so the rest of the page goes back to the main post. - Avoid
query_posts(), as it replaces the main query and causes bugs. To change the main query, use thepre_get_postsaction instead. - Don't set
posts_per_pageto -1 on big sites, because loading every post at once can slow down your pages.
WP_Query works with custom post types too. Read our guide on how to query custom post type in WordPress to see it in action.
That's how WP_Query works. With a few arguments, you can pull almost any set of posts you need. If something doesn't work as expected, tell us in the comment box below.