I’m trying to change the sort order of staff members using post meta. This works just fine on the main staff archive page but I can’t get it working on staff category archives. I’ve tried this:

add_action( 'pre_get_posts', 'cd_sort_staff' );
     function cd_sort_staff( $query ) {
         if ( $query->is_main_query() && !is_admin() && $query->query_vars['post_type'] == 'staff' ) {
            $query->set('orderby', 'meta_value_num');  
            $query->set('meta_key', 'sort_order');  
            $query->set('order', 'ASC'); 
    }
} 

And this:

add_action( 'pre_get_posts', 'cd_sort_staff' );
function cd_sort_staff( $query ) {
    if ( $query->is_main_query() && !is_admin() && is_post_type_archive('staff') ) {
        $query->set('orderby', 'meta_value_num');  
            $query->set('meta_key', 'sort_order');  
            $query->set('order', 'ASC'); 
    }
} 

Both work fine on the main /staff/ archive page. But neither work on /staff_category/category-name the posts are sorted based on post date only.

1 Answer
1

Since you need to target the post type archive page and taxonomy pages, you just need to extend your function to include the specific taxonomy archive pages. You can use is_tax() to target these taxonomy pages

You can try the following; (You can just modify is_tax() to target specific taxonomies or terms according to documentation)

add_action( 'pre_get_posts', 'cd_sort_staff' );
function cd_sort_staff( $query ) {
    if ( $query->is_main_query() && !is_admin() ) {
        if ( $query->is_tax() || $query->is_post_type_archive('staff') ) {
            $query->set('orderby', 'meta_value_num');  
            $query->set('meta_key', 'sort_order');  
            $query->set('order', 'ASC'); 
        }       
    }
} 

Leave a Reply

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