admin管理员组文章数量:1332383
How can I display only the specific category when accessing the posts related to that category? For example, I want to show only CSR Events under Categories When accessing posts related to CSR events. Here's the link to CSR post /
Screenshot: .jpg
Similarly, when visiting posts related to other categories, only the specific category will be shown.
How can I display only the specific category when accessing the posts related to that category? For example, I want to show only CSR Events under Categories When accessing posts related to CSR events. Here's the link to CSR post https://www.mi-eq/blood-donation-compaign/
Screenshot: https://i.sstatic/YoTfk.jpg
Similarly, when visiting posts related to other categories, only the specific category will be shown.
Share Improve this question asked Jun 26, 2020 at 1:58 David LeeDavid Lee 92 bronze badges2 Answers
Reset to default 0I have copied and pasted your code to function.php but it turned out to be no categories shown. Please see screenshot here - https://ibb.co/gZt2zQF . Anything wrong with the code? Can anyone else help?
Here's some code that will modify the arguments for the WP Categories widget so that the only category displayed will be the current category. Add this to your theme's/child theme's functions.php
or create a plugin for this code:
/**
* 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 );
Example with this code enabled:
Example without code enabled (cropped because there are lots of categories):
本文标签: How to display specific category on single post page
版权声明:本文标题:How to display specific category on single post page? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742303628a2449481.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论