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:
$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.
thats work for me:
the full code: