我们可以通过映射category_name
查询变量(从pretty permalinks设置)到category__in
(忽略子类别):
function wpse_184127_ignore_category_children( $wp_query ) {
if ( $wp_query->is_main_query() && $wp_query->is_category() && $name = $wp_query->get( \'category_name\' ) ) {
if ( $term = get_term_by( \'slug\', sanitize_title_for_query( $name ), \'category\' ) ) {
if ( $term->parent )
$depth = count( get_ancestors( $term->term_id, \'category\', \'taxonomy\' ) );
else
$depth = 0;
if ( $depth <= 1 ) {
$wp_query->set( \'category__in\', array( $term->term_id ) );
unset( $wp_query->query_vars[\'category_name\'] );
}
}
}
}
add_action( \'pre_get_posts\', \'wpse_184127_ignore_category_children\' );
Update: 增加了深度检查。只要换一下
$depth <= 1
到你需要的任何表达。目前,它只会忽略顶级和一级类别的子级(即深度小于或等于1)。