WordPress – get posts ordered by meta value

I try to get posts from wp database order by meta value.
The problem is that some posts have meta key in database and some not.

I try this code:

Read More
$args = array(
        'post_type' => 'post',
        'meta_key' => 'top',
        'meta_query' => array(
            'relation' => 'OR',
            array(
                'key' => 'top',
                'compare' => 'NOT EXISTS',
                'value' => ''
            ),
            array(
                'key' => 'top',
                'value' => '1'
            )
        ),
        'orderby' => '1'
    );
    $posts = new WP_Query($args);

This show posts but nor ordered by meta key.

For better explain, I want some posts to show always on top or at the front. So I add meta key named ‘top’. This is work OK – also I have looked into database and meta key is updating correctly. If post is TOP than it has meta key with value 1, if not then there is no meta key named ‘top’ for this post.

So how can I order posts with meta key like that?

Thanks.

Related posts

Leave a Reply

1 comment

  1. thats work for me:

    query_posts('meta_key= top&orderby=meta_value');
    

    the full code:

      <?php 
    query_posts('meta_key=facebook_likes&orderby=meta_value');
    ?>    
    <?php while (have_posts()) : the_post(); ?>
    
    <div class="post">
    <h2 class="postTitle"><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
    <div class="postMeta">
    <span class="date"><?php the_time('M.d, Y') ?></span> in
    <span class="filed"><?php the_category(', '); ?></span>
    </div>
    <div class="postContent"><?php the_content(); ?></div>
    <p class="comments"><?php comments_popup_link(); ?></p>
    </div> <!-- Closes Post -->