WP_Query: advanced arguments for real projects
WP_Query is the main way to get posts in WordPress. Beyond post_type and posts_per_page it can combine taxonomy conditions, filter by custom fields and dates, sort by a field and exclude posts. These are the patterns that come up in almost every project.
Problem: A template needs a list of posts by several conditions at once: some categories but not a tag, a price range, the last 30 days, related posts without the current one.
Solution: Use tax_query, meta_query (with named clauses for sorting), date_query and post__not_in in a new WP_Query, and call wp_reset_postdata() after the loop.
Several post types and taxonomy conditions
<?php
$query = new WP_Query( array(
'post_type' => array( 'post', 'portfolio' ),
'posts_per_page' => 10,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( 'news', 'case-studies' ),
'operator' => 'IN',
),
array(
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => array( 'internal' ),
'operator' => 'NOT IN',
),
),
) );
A post type that does not have one of the taxonomies drops out of an IN condition: portfolio items are found here only if category is registered for them.
A range of a custom field, sorted by it
Named clauses (keys instead of numbers) can be used in orderby:
<?php
$query = new WP_Query( array(
'post_type' => 'course',
'meta_query' => array(
'relation' => 'AND',
'price_clause' => array(
'key' => 'price',
'value' => array( 10, 100 ),
'type' => 'NUMERIC',
'compare' => 'BETWEEN',
),
'level_clause' => array(
'key' => 'level',
'value' => 'beginner',
),
),
'orderby' => array( 'price_clause' => 'ASC' ),
) );
For WooCommerce products use wc_get_products() instead: since WooCommerce 3.0 “featured” and visibility are taxonomy terms, not meta fields, and the price lookup is better left to WooCommerce.
The last 30 days
<?php
$query = new WP_Query( array(
'post_type' => 'post',
'date_query' => array(
array(
'after' => '30 days ago',
'inclusive' => true,
),
),
) );
Related posts without the current one
<?php
$related = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' => 4,
'post__not_in' => array( get_the_ID() ),
'ignore_sticky_posts' => true,
'no_found_rows' => true, // no pagination needed: skip counting all matches
'category__in' => wp_get_post_categories( get_the_ID() ),
) );
while ( $related->have_posts() ) {
$related->the_post();
the_title( '<h3><a href="' . esc_url( get_permalink() ) . '">', '</a></h3>' );
}
wp_reset_postdata();
no_found_rows saves a second query for every list that has no pagination. For changing the main query of an archive, use pre_get_posts instead of a new query, see changing the arguments of the global query.
NOTE: Always call wp_reset_postdata() after a custom loop. the_post() overwrites the global $post, and without the reset the template functions after the loop (comments, sidebar widgets) work with the last related post instead of the current page.