How to fetch Any post with WP_Query in WordPress?

Harish Kumar · · 2701 Views

WP_Query is your buddy. It allows you to get content from the database according to your requirements. In this article, I will explain top to bottom about how WP_Query works. let’s get started!

A Custom Loop

The key to working well with customized queries is mastering the arguments you can pass to them. The loop on a regular archive page would look something like this:

<?php if ( have_posts() ) : ?>
	<?php while( have_posts() ) : the_post() ?>
		<!-- Display Post Here -->
	<?php endwhile ?>
<?php else : ?>
	<!-- Content If No Posts -->
<?php endif ?>

When the page is loaded, WordPress has already retrieved the correct posts. For custom queries, we’ll need a custom loop. The code is very similar, here goes:

<?php 
$args = array( 
	'post_type'   => 'post',
	'post_status' => 'future'
);
$result = new WP_Query( $args );
if ( $result->have_posts() ) : 
?>
	<?php while( $result->have_posts() ) : $result->the_post() ?>
		<!-- Display Post Here -->
	<?php endwhile ?>
<?php else : ?>
	<!-- Content If No Posts -->
<?php endif ?>

For the new WordPress query, we use the WP_Query class. It requires some parameters to specify the types of posts we need. Then, we call the have_posts() and the_post() methods on our $result object.

Simple Arguments

A few parameters are entirely simple, for example, the tag or tag_id. The former takes a tag slug, the later a tag id. You can likewise separate multiple items with commas or use negative ids to indicate that you need to fetch posts that don't have that specific tag attached.

$args = array( 
	'post_type'   => 'post',
	'tag_id'      => '22,92,44,-21'
);
$our_posts = new WP_Query( $args );

The snippet would retrieve posts which have any of the first three tags attached to them, but not the 4th. 

The author, author_name, cat, category_name, s (for search terms), post_status, post_type are examples of some simpler fields. Some fields, like post_status, need you to pass an array of statuses if you want to use multiple values.

$args = array( 
	'post_type'   => array( 'post', 'page' ),
	'post_status' => array( 'draft', 'publish' ),
	'cat'         => 'music,videos'
);
$our_posts = new WP_Query( $args );

Taxonomy Queries

For easy things, using the described arguments to retrieve content depending on categories or tags is enough, but what if you have a custom taxonomy, or you need to combine multiple parameters? The answer depends on the tax_query argument, which is an array.

$args = array(
	'post_type' => 'book',
	'tax_query' => array(
		array(
			'taxonomy' => 'genre',
			'field'    => 'slug',
			'terms'    => array( 'scifi', 'thriller' ),
			'operator' => 'NOT IN',
		),
		array(
			'taxonomy' => 'author',
			'field'    => 'id',
			'terms'    => array( 92, 883, 399 ),
		),
		'relation' => 'AND',
	),
);
$query = new WP_Query( $args );

Here above code snippet retrieve some posts from our ‘book’ post type, including some taxonomy parameters using two arrays defined within the tax_query. In the query, we specified that to fetch books written by the author’s 73, 65, or 197, which are not in the sci-fi or thriller category. The relation parameter describes the relationship between the two arrays. In our case, it is an ‘and’ relationship, which means that both circumstances must be true.

If we used or, then it will retrieve books, which are either not in the sci-fi or thriller category. Or they are written by the specified three authors.

Meta Queries

Meta queries are very similar to taxonomy queries in structure, but they use data from the post meta table to filter posts. The snippet below will fetch all published posts which have a featured image.

$args = array(
	'post_type' => 'post',
	'meta_query' => array(
		array(
			'key'     => '_thumbnail_id',
			'value'   => '',
			'compare' => '!=',
		),
	),
);
$query = new WP_Query( $args );

WordPress stores the ID of the featured image for a post using the _thumbnail_id field. So in the above code snippet, we retrieve all posts where the _thumbnail_id meta value is not empty.

In the above code snippet, we can learn that for compare property and type, we can use a multitude of values that should be familiar from SQL, such as =, !=, >, >=, <, <=, LIKE, NOT LIKE, IN, NOT IN, BETWEEN, NOT BETWEEN, EXISTS (from WordPress 3.5 and up), and NOT EXISTS (from WordPress 3.5 and up). To compare numbers or dates, we use type property. And possible values of type property are NUMERIC, BINARY, CHAR, DATE, DATETIME, DECIMAL, SIGNED, TIME, UNSIGNED. Just similar to taxonomy queries. We can stack multiple specifications and then use relation parameters to specify the relationship between them.

Just similar to taxonomy queries, we can stack multiple specifications and then use relation parameters to specify the relationship between them.

$args = array(
	'post_type' => 'post',
	'meta_query' => array(
		'relation' => 'OR',
		array(
			'key'     => 'mood',
			'value'   => array( 'happy', 'awesome' ),
			'compare' => 'IN',
		),
		array(
			'key'     => 'income',
			'value'   => 500,
			'compare' => '>',
			'type'    => 'NUMERIC'
		),
	),
);
$query = new WP_Query( $args );

Date Parameters

Dates can get a bit complicated but are very flexible. The WP_Query Documentation has a lot of illustrations if you need more details.

We can use the year, month number, w (week of the year), day, and a couple of other parameters for retrieving posts from a time.

Example 1: Retrieving all posts from the March of 2013

$args = array(
	'post_type' => 'post',
	'year' => 2013,
	'month' => 3
);
$query = new WP_Query( $args );

Example 2: Retrieving posts written between 9AM and 5PM on weekdays.

$args = array(
	'post_type' => 'post',
	'date_query' => array(
		array(
			'hour'      => 9,
			'compare'   => '>=',
		),
		array(
			'hour'      => 17,
			'compare'   => '<=',
		),
		array(
			'dayofweek' => array( 2, 6 ),
			'compare'   => 'BETWEEN',
		),
	),
);
$query = new WP_Query( $args );

Ordering Results

For ordering results, WordPress provides us order_by and order parameters. And the order parameter is straightforward. You can use ASC or DESC to order ascending or descending.

The possible values for order_by parameter cab be: none, ID, author, title, name, type, date, modified, parent, rand, comment_count, menu_order, meta_value, meta_value_num, post__in.

Ordering by meta_value can be especially useful. In this case, It required to specify the meta_key field as well.

Example 1:

$args = array(
	'post_type' => 'painting',
	'meta_query' => array(
		array(
			'key'     => 'price',
			'value'   => 50000,
			'compare' => '>',
			'type'    => 'NUMERIC'
		),
	),
	'order_by' => 'meta_value_num',
	'meta_key' => 'price'
);
$query = new WP_Query( $args );

Example 2:

$args = array(
	'post_type' => 'post',
	'post__in' => array( 23, 441, 12, 322, 34, 33),
	'order_by' => 'post__in',
);
$query = new WP_Query( $args );
0

Please login or create new account to add your comment.

0 comments
You may also like:

Data Integration Tools

An ocean of data integration tools that promise to be “the best” makes it easy to get confused. Based on research, usage experience, and popular ratings, we have compiled a (...)
Narola Infotech

How to Build Flutter App for any WordPress Site

Leaving a perfect digital footprint is crucial for brand growth. However, you may be here to find the optimal balance between mobile engagement and web traffic. It’s possible (...)
Narola Infotech

The Benefits of Using Hospital Management Software in 2024: A Guide for Healthcare Providers

In the ever-evolving healthcare landscape, integrating technology has become imperative for efficient and effective patient care. One such technological advancement that has revolutionized (...)
anika

Types of Web Applications With Examples And Industry Use Cases

Whether it’s about driving more revenue for your business or strengthening your branding game, an impactful online presence is crucial. To make sure this is done right, there (...)
Narola Infotech

Use Transients API Caching and Speed Up Your WordPress Theme.

The Transients API in WordPress is an effective method for saving cached data in the database. It allows us to take resource-intensive queries and store them in short-term caches (...)
Harish Kumar

Remove api.w.org REST API/JSON API from WordPress header.

WordPress uses the REST API since edition 4.4 of the CMS. It allows developers to interact with the WordPress back-end more quickly since this API is a standard way to connect. (...)
Harish Kumar