I'm attempting to order posts by meta data, which is working fine, but the posts without the meta are not shown.

I've tried a couple of guides on Stack Exchange that come up with a quick Google, of which people say they work fine, but adding to my site, the code just does not want to show posts without the meta data.

What I'm trying to achieve is essentially a sticky post, so when a user clicks "Pin Post", a piece of post meta data is stored as "pin_".$user (so it is unique on this post) with a value of "1".

I would like to show posts that have the value "1" at the top, subsequently ordered by date, after which all other posts without the meta data should be shown, in date order.

I realise this code is incomplete, but here is what I have so far;

query_posts(array('post_type' => array('beauty', 'health', 'food'), 'author_in' => $follow, 'orderby' => 'meta_value_num',
        'meta_key' => 'pin_'.$user, 'showposts' => -1, 'order' => 'DESC')); if ( have_posts() ) : while ( have_posts() ) : the_post(); 

How would I adapt this to produce the desired result?

2 Answers 2


First: don't use query_posts. It will confuse the main WordPress loop.

You will need two queries. First use the query you have already constructed to get the priority posts:

$query1 = new WP_Query( $args ); // here use the $args you already have

Now count how many posts are returned to set the maximum return on the second query:

$count = $query1->post_count;
$args = array ('posts_per_page'=>15-$count) // and any other arguments you may want to parse
$query2 = new WP_Query( $args );

Now loop through both queries to display them. Note that if you need pagination you will have to do some more clever stuff to make sure you get the right posts and amount of posts on your page.


You'll want to create a new query instead and use the meta_query parameter.

Something like this should get you going (untested). See WP_Query() for more examples and parameters.

$args = array(
  'post_type' => array(
    'beauty', 'health', 'food',
  'author'     => $follow, 
  'orderby'    => 'meta_value_num',
  'meta_key'   => 'pin_'.$user,
  'showposts'  => -1,
  'order'      => 'DESC',
  'meta_query' => array(
    'relation' => 'OR',
     'key'      => 'pin_'.$user',
     'compare' => 'NOT EXISTS',

$query = new WP_Query( $args );

// The loop
if ( $query->have_posts() ) {
  // do something
} else {
  // no posts found

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.