如何在单个帖子页面上显示特定类别?

时间:2020-06-26 作者:David Lee

在访问与该类别相关的帖子时,如何仅显示特定类别?例如,在访问与CSR事件相关的帖子时,我只想在类别下显示CSR事件。这是CSR帖子的链接https://www.mi-eq.com/blood-donation-compaign/

屏幕截图:https://i.stack.imgur.com/YoTfk.jpg

同样,当访问与其他类别相关的帖子时,只会显示特定类别。

2 个回复
SO网友:Dave Romsey

下面的一些代码将修改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 );
启用此代码的示例:enter image description here

未启用代码的示例(由于存在大量类别而被裁剪):enter image description here

SO网友:David Lee

我已将您的代码复制并粘贴到函数中。php,但结果没有显示类别。请参见此处的屏幕截图-https://ibb.co/gZt2zQF . 代码有什么问题吗?其他人能帮忙吗?

相关推荐