Setting orderby to a custom field using pre_get_posts

I’m using the ACF plugin to create custom fields which get applied to a custom post type (projects). In my functions.php file I am trying to use pre_get_posts to change the order of my custom post type archive using a custom field.

function apply_projects_query_filter ($query)
{
    if (is_admin()) {
        return $query;
    }

    if (is_archive() && $query->query_vars['post_type'] == 'projects' && $query->is_main_query()) {

        $query->set('orderby', 'meta_value');
        $query->set('meta_key', 'project_status');       
        $query->set('order', 'DESC');
    }

    return $query;
}
add_action('pre_get_posts', 'apply_projects_query_filter');

My project_status custom field has the possible values of 0 or 1. Using the code above returns no results at all. What am I doing wrong?

1 Answer
1

Not sure exactly why, but by adding another filter using the meta_query it all started working. I now only get posts in my custom post type archive that do not have the project_update field set and are ordered by project_status. This is what I was after.

$meta_query = array(
    array(
       'key'=>'project_update',
       'value'=>'1',
       'compare'=>'!=',
    )
);

$query->set('meta_query', $meta_query);

Leave a Comment