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?

Read more here:: Setting orderby to a custom field using pre_get_posts

Leave a Reply

Your email address will not be published. Required fields are marked *