WordPress WP_Query Class: Query Posts by Condition

By | September 20, 2020

WordPress WP_Query Class allows us to query posts by different query condtions. In this tutorial, we will use some examples to show you how to this class to query posts.

Syntax of WP_Query

$query1 = new WP_Query( $args );

WP_Query will receive a php array $args to query posts.

The $args can be:

array( 'author_name' => 'rami' )
array( 'category__in' => 4 )
array( 'cat' => '2,6,17,38' )

To know full list of $args, you can refer this tutorial:

A Full List of WordPress WP_Query Query Arguments ($args)

How to use WP_Query to query posts?

The basic usage of WP_Query is:

<?php
$args = array( 'author' => 123 ) 
// The Query
$the_query = new WP_Query( $args );
 
// The Loop
if ( $the_query->have_posts() ) {
    echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Where $args can be replaced by your own condition.

You should notice:

1. The query result of WP_Query should be got in a loop.

2. wp_reset_postdata() must be set at the end of the query.

Leave a Reply

Your email address will not be published. Required fields are marked *