下面的一些代码将修改WP Categories小部件的参数,以便显示的唯一类别将是当前类别。将此添加到主题/子主题functions.php
或为此代码创建插件:
/**
* Modify the arguments for the Categories widget on single templates so that
* only the current category is returned.
*
* @param array $cat_args Arguments passed to wp_list_categories(),
* @param array $instance Category widget instamce.
*
* @return array wp_list_categories() arguments.
*/
function wpse_widget_categories_args( $cat_args, $instance ) {
// Bail if this isn\'t the single template.
if ( ! is_single() ) {
return $cat_args;
}
global $wp_query;
// Get term id for current category.
$current_term = get_term_by(
\'slug\',
$wp_query->query[\'category_name\'],
\'category\'
);
// Get term objects for all terms except the current term.
$exclude_categories = get_categories(
[
\'exclude\' => [ $current_term->term_id ],
]
);
// Use our list of excluded terms to ensure results are only returned for the current term.
$cat_args[\'exclude\'] = wp_list_pluck( $exclude_categories, \'term_id\' );
return $cat_args;
}
add_filter( \'widget_categories_args\', \'wpse_widget_categories_args\', 10, 2 );
启用此代码的示例:
未启用代码的示例(由于存在大量类别而被裁剪):