2

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

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);
1
  • You can (and should - to mark the question as answered) accept your own answers, btw. Though it'd be better if the answer contained a better explanation of what you did to solve the problem! Like... where/how you added that missing bit.
    – Kay
    Aug 6, 2018 at 13:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.