WordPress WP_Query: Get Posts by Meta Values

As you know all the posts have the metadata you can fill in “Custom fields” metabox (it can also be hidden). So, for example, if you want to get a post with meta key show_in_slider and meta value true, you can do it in the following way:

<?php
$args = array(
	'meta_key' => 'show_in_slider',
	'meta_value' => 'true'
);
 
$allRecords = new WP_Query( $args );
?>

Otherwise, if you need to query all posts except the ones with this pair of meta key and value, you can use the following parameters:

<?php
$args = array(
	'meta_key' => 'show_in_slider',
	'meta_value' => 'true',
	'meta_compare' => '!='
);
 
$allRecords = new WP_Query( $args );
?>

Do not forget that all examples in this post are simplified, so, some of WP_Query parameters are missing, e.g posts_per_page or post_type.

This was very simple examples, just an introdution. But this post is about meta_query parameter. This parameter allows us to create a really cool post filters and search scripts.

meta_query Usage Examples

Get Posts with a Specific Custom Field Value

This is a simple example. Let’s get all the posts with custom field name “color” and custom field value “white”.

<?php 
// the meta_key 'blog_type' with the meta_value 'clasic'
$args = array(
	'meta_query' => array(
		array(
			'key' => 'blog_type',
			'value' => 'clasic'
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Get all the posts except the ones with meta key “blog_type” and meta value “clasic”:

<?php
$args = array(
	'meta_query' => array(
		array(
			'key' => 'blog_type',
			'value' => 'clasic',
			'compare' => '!='
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Now let’s get all the posts with clasic OR regular type custom field value:

<?php
// custom field name is blog_type and custom field value is 'clasic' OR 'regular'
$args = array(
	'meta_query' => array(
		array(
			'key' => 'blog_type',
			'value' => array('clasic','regular'),
			'compare' => 'IN'
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Get all the posts except clasic and regular posts:

<?php
$args = array(
	'meta_query' => array(
		array(
			'key' => 'blog_type',
			'value' => array('clasic','regular'),
			'compare' => 'NOT IN'
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Get Posts Within a Given Range of Numeric Meta Values

For example, let’s filter the post by hit’s rang:

<?php
// The post hit's is more than 9000 and less than 10000
$args = array(
	'meta_query' => array(
		array(
			'key' => 'hits',
			'value' => array( 9000, 10000 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Numeric Comparison

The post hit’s in this example is 9999 or more than 9999:

<?php 
$args = array(
	'meta_query' => array(
		array(
			'key' => 'hits',
			'value' => 9999,
			'type' => 'numeric',
			'compare' => '>='
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

The post hit’s less than 100:

<?php
$args = array(
	'meta_query' => array(
		array(
			'key' => 'hits',
			'value' => 100,
			'type' => 'numeric',
			'compare' => '<'
		)
	)
);
 
$allRecords = new WP_Query( $args );
?>

Query Posts by Two Or More Custom Field Values

Let’s combine some of the previous examples:

<?php
// the 'blog_type' is 'clasic' AND the 'hits' is more than 9900 and less than 10000
$rd_args = array(
	'meta_query' => array(
		'relation' => 'AND',
		array(
			'key' => 'blog_type',
			'value' => 'clasic'
		),
		array(
			'key' => 'hits',
			'value' => array( 9900, 10000 ),
			'type' => 'numeric',
			'compare' => 'BETWEEN'
		)
	)
);
 
$rd_query = new WP_Query( $rd_args );
?>

I think, all above examples are sufficient. If any one have any issue then put your comments bellow.

Get Popular Posts by Views in WordPress

In the past we have shown you how to get popular post in WordPress. In this article, we will show you how to track and display popular posts by views in WordPress without using any plugins.

First thing we need to do is create a function that will detect post views count and store it as a custom field for each post. To do this, paste the following codes in your theme’s functions.php file

//This function will count post views. there is one parameter postID
function SetPostViews($postID) {
    $meta_key = 'post_views_count';
    $count = get_post_meta($postID, $meta_key, true);
    if($count==''):
        $count = 0;
        delete_post_meta($postID, $meta_key);
        add_post_meta($postID, $meta_key, '0');
    else:
        $count++;
        update_post_meta($postID, $meta_key, $count);
    endif;
}
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);

Now that you have a function in your function file, now we need to call this function on post details pages.To do this, you would need to paste the following code inside your post details loop:

SetPostViews(get_the_ID());

Once you have placed this, every time a user visits the post, the custom field will be updated.

Now we need to show top 5 viewed post. To do this, you would need to paste the following code inside your function file

//This function will show top viewed post. there is one parameter "QTY" length of showed post.
function GetPopularPost($QTY){
$popularpost = new WP_Query( array( 'posts_per_page' => $QTY, 'meta_key' => 'post_views_count', 'orderby' => 'post_views_count', 'order' => 'DESC'  ) );
while ( $popularpost->have_posts() ) : $popularpost->the_post();
echo get_the_title();
endwhile;
}

At this time you have a function for show popular posts. just call this function where you want to show popular posts.

GetPopularPost("5");

Get Related Post In WordPress

If you want to show related post then there are two methods of doing so and you can choose whichever method you prefer. One way is doing it without a plugin and then there is another method that is doing it with a plugin.

Display Related Posts in WordPress with WP_query()

  • Open your theme function file and put this code into function file.

    <?php
    //This function will print related post. there is two parameters 1st is Post ID 2nd is QTY (Quantity)
    function getRelatedPost($ID,$QTY) {
    
        $tags = wp_get_post_tags($ID);
        if ($tags):
            $first_tag = $tags[0]->term_id;
            $args = array(
                'tag__in' => array($first_tag),
                'post__not_in' => array($ID),
                'showposts' => $QTY,
                'caller_get_posts' => 1
            );
            $my_query = new WP_Query($args);
            if ($my_query->have_posts()):
                $HTML = "";
                while ($my_query->have_posts()) : $my_query->the_post();
                    $HTML .= '<a href="'.the_permalink().'" rel="bookmark" title="'.the_title_attribute().'">'.the_title().'</a>';
                endwhile;
            endif;
            wp_reset_query();
        endif;
        echo $HTML ;
    }
    ?>
    
  • Call this function into your single.php file and pass the post id and post length.
    <?php getRelatedPost($post->ID,'5'); ?>

Display Related Posts in WordPress with plugin

The plugin we use is called Yet Another Related Post Plugin (YARP). It gives you a list of posts and/or pages related to the current entry, introducing the reader to other relevant content on your site. for more details please visit on plugin site.Yet Another Related Post Plugin