Question

I have a custom post type, books, set up and a custom taxonomy, book_cat, to act as categories for these posts. I've added the below code to functions.php to sort posts on my custom taxonomy archive page by an Advanced Custom Fields date field – and this works like a charm, but only when I remove the conditional code targeting the books post type, I can't seem to work out why.

/*when listing books, show them in publication order*/
function my_pre_get_posts( $query ) {
    
    // do not modify queries in the admin
    if( is_admin() ) {
        return $query;
    }

    // only modify queries for 'books' post type
    if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'books' ) {
        $query->set('orderby', 'meta_value');   
        $query->set('meta_key', 'published');    
        $query->set('order', 'ASC');
    }

    // return
    return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');
Was it helpful?

Solution

If you want to filter the query for a taxonomy archive, you should check if the query is for that archive:

if ( $query->is_tax( 'book_cat' ) ) {
    $query->set('orderby', 'meta_value');   
    $query->set('meta_key', 'published');    
    $query->set('order', 'ASC');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top