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):