Sorting Posts by Custom Field is not working properly in WordPress

80 Views Asked by At

I have WordPress posts and I have Boolean Advanced Custom Field for each, which changes the status of being featured for each university post. So when outputting them, I want to show the featured ones (more clearly, the ones which have the featured field set to true) first. But when I'm doing it, WordPress is showing me 8 posts, but not 10 (as I wrote), even though I have enough posts. What can be causing the issue?

$args = array( 
    'post_type' => 'university', 
    'post_status' => 'publish', 
    'posts_per_page' => 10, 
    'meta_key' => 'featured', 
    'orderby' => 'meta_value', 
    'order' => 'DESC' 
);

I tried browsing and asking ChatGPT, but I didn't find any working solution yet.

1

There are 1 best solutions below

1
Chad Phillips On

In a WordPress query, if you order by a meta_value, posts that do not have this meta_value set will be excluded from the results. Even if you set the default value of a boolean custom field to false, this value is not set on a post until you update that post. So, you have to open all posts and save a value (true or false) for this meta_value, or run a script to set this value on all posts where you haven't yet set a value.