WP Query

WP_Query is a powerful class in WordPress used to query and retrieve posts (or any custom post types) from the database. It allows developers to build custom loops beyond the default one used by WordPress.

What Does It Do?

  • Fetches posts based on specific criteria (category, tag, post type, date, custom fields, etc.)
  • Allows full control over what content is displayed, how many items, what order, and more
  • Often used to replace or extend the default WordPress Loop

Basic Example

$args = [
    'post_type' => 'post',
    'posts_per_page' => 5,
];

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        the_title('<h2>', '</h2>');
        the_excerpt();
    }
    wp_reset_postdata();
}

Common WP Query Parameters

ParameterDescription
post_type'post', 'page', 'your_cpt', etc.
posts_per_pageNumber of posts to show
category_nameFilter by category slug
orderby, orderSorting (e.g., date, title, ASC)
meta_queryQuery by custom fields (ACF, etc.)
tax_queryFilter by taxonomy terms
pagedSupport for pagination
date_queryFilter by date range

When to Use WP_Query

  • Displaying custom post types like testimonials or events
  • Building custom archive or filtered pages
  • Creating sliders, carousels, or widgets with specific content
  • Replacing the default loop in a theme

Always Reset Post Data

When using WP_Query outside of the main loop, remember to call:

wp_reset_postdata();

This ensures that global post data is not altered for the rest of the page.

When Not to Use

  • Inside main loop: use have_posts() and the_post() instead
  • For simple cases: consider helper functions like get_posts() or query_posts() (although query_posts() is discouraged)
FeatureDescription
PurposeFetch and loop through custom content
Use caseFull control over queried post data
Best practiceAlways reset post data after usage
Related toThe Loop, get_posts(), query_posts()