Zozo Zozo
Zozo Zozo

Reputation: 151

Wordpress query custom meta key

I've added a postmeta (popular_posts) see image below. But when I query posts with meta key "popular_posts" like in below I've had no result:

new WP_Query(array( 'meta_key'=>'popular_posts' ))

Some one can explain me how to properly retrieve that have meta key "popular_posts" ?

enter image description here

Upvotes: 0

Views: 13398

Answers (2)

Rakesh Roy
Rakesh Roy

Reputation: 970

    $popular_posts_args = array(
      'post_type' => 'post',
      'orderby'   => 'meta_value',
      'order' => 'DESC',
      'meta_query' => array(
           'meta_value' => array(
                'key' => 'popular_posts',
                'type' => 'NUMERIC' 
    )));

    $popular_posts = new WP_Query($popular_posts_args);

As your meta key store numeric value. It is better to define the type in the argument. Then you can loop through $popular_posts

Upvotes: 1

Lathiya Fenil
Lathiya Fenil

Reputation: 290

This is the simple way to get post by their meta.

$myquery = new WP_Query( "post_type=post&meta_key=popular_posts");

Or You can use this :

$second_loop = get_posts( array(
  'meta_key'   => 'popular_posts',
  'meta_value !=' => '',

) );

Upvotes: 5

Related Questions