How to fetch Any post with WP_Query in WordPress?
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
parameter cab be: order_by
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 );
Please login or create new account to add your comment.