0
votes

I have number of posts in post_type="post". I want to display all posts using WP_query on one page but those posts have customfield name="pinned_to_top" that should come first in loop and other posts without this custom field will come down.

I have tried to use of orderby but i can't do that.

I am using this code but it will give me posts only those have custom field="pinned", not other posts.

$query = array(
    'category_name' => 'blog',
    'paged'=> $paged,

     'meta_query' => array(
        array(
            'key'     => 'pinned',
            'value'   => 'yes',
            'compare' => 'OR',
        ),
        ),
    'posts_per_page' => '10',
);
$wp_query = new WP_Query($query);

Main motive to add this custom field is that, I want some Important posts at the top in LOOP.

Let me know if anyone have experienced it?

1
why do not just create 2 loops. 1st with only custum fielded with pinned_to_top, and in the second exlude those. - vaso123
I am also using pagination, posts should not repeat again. thats why i am not using two loops. - Vikas Rana
Use usort to sort the returned $posts before the loop - Pieter Goosen

1 Answers

0
votes

I think you should do something like in the codex. I've did not try this, but i think there will be the solution somewhere...

$query = array(
'category_name' => 'blog',
'paged'=> $paged,

 'meta_query' => array(
    array(
        'key'     => 'pinned',
        'value'   => 'yes',
        'compare' => 'IN',
    ),
    array(
        'key'     => 'pinned',
        'value'   => 'yes',
        'compare' => 'NOT IN',
    ),
 ),
'posts_per_page' => '10',

);

But in your case need to use the first is IN, and for the sencond is NOT IN. So use 2 arrays.

If it does not works, check the http://codex.wordpress.org/Class_Reference/WP_Query and the meta_compare section. Maybe you should use == and !=.