Wordpress - CPT 和分类法页面上的自定义顺序

Wordpress - Custom order on CPT and Taxonomy pages

我正在创建一个函数来订购特定的自定义 post 类型(例如:产品)。它在 CPT 存档页面上运行良好,但在自定义分类页面(例如:类别)上不起作用:

function my_pre_get_posts( $query ) {

// do not modify queries in the admin
if( is_admin() ) {

    return $query;

}

// only modify queries for 'produit' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'produit') {

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

}

// return
return $query;

}

add_action('pre_get_posts', 'my_pre_get_posts');

如何附加我的代码以便自定义顺序也适用于我的自定义分类页面?

非常感谢

您需要使用 is_tax() 函数来检查它是否是您要更改排序顺序的分类档案。所以像这样...

if ( $query->is_tax( 'produit-category' ) && $query->is_main_query() ) {

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