I have the following wp_query:
$args = array(
'post_type' => 'news',
'orderby' => 'meta_key',
'order' => 'ASC',
'meta_key'=>'custom_author_name',
'post_per_page'=>-1
);
$query = new WP_Query($args);
echo $query->found_posts;
echo = 10 results because there are only 10 news
posts with a meta_key = custom_author_name
. But there are hundreds of news
posts that don’t have a post_meta row with that specific meta_key. Please notice, that there is no meta_query involved. No meta_value is assigned, because I am only trying to sort the posts by meta_key, and not filter by meta_value.
Shouldn’t orderby select all posts? and just order them?
If so why is the result filtered? If the meta_key is not found, why not just use an empty string, or a match all?
If not, why not?
If I enter a meta_key to every news post (even if it’s an empty string) then I get the expected result. But that seems like a whole lot of table rows that don’t need to be there.
4 s
As stated in @ambroseya’s answer, its supposed to work like that. Once you declare a meta query, even if you aren’t looking for a specific value, it will only query posts with that meta key declared. If you want to include all posts sort them by the meta key, use the following code:
$args = array(
'post_type' => 'news',
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
'relation' => 'OR',
array(
'key'=>'custom_author_name',
'compare' => 'EXISTS'
),
array(
'key'=>'custom_author_name',
'compare' => 'NOT EXISTS'
)
),
'posts_per_page'=>-1
);
$query = new WP_Query($args);
echo $query->found_posts;
What this does is use an advanced meta query that looks for posts that do and don’t have that meta key declared. Since the one with EXISTS
is first, when you sort by meta_value
, it’ll use the first query.