0

This is my code for showing categories on post meta:

$categories_list = get_the_category_list(  ', ', 'ixn' );
printf( '<span class="cat-links">' . ( 'Category: %1$s', 'ixn' ) . '</span>', $categories_list ); 

('ixn' is the theme name)

Is there a simple way to hide a specific category, called "site" from the categories that appear on the post meta?

I have read these supposed solutions, but they may be overkill for what I need and don't fit well with my code as they don't use the get_the_category_list:

2

From quick look through related functions I don't think there is one that retrieves terms for the post and allows explicit exclusion.

However there is a convenient filter the_category_list right inside the function you use, with array of category objects, before they are turned into HTML output.

This should be a very fitting place to check the array and exclude the category you wish to skip. As always take care to only add your filter within required context or check for context within it.

  • You definitely hit the nail on the head. Problem is I don't know how or where to use the apply_filters( 'the_category_list', array $categories, int|bool $post_id ) function. – IXN Oct 19 '17 at 12:09
  • That's what core uses already, you would need to hook into it. :) I would recommend to go through documentation on hooks in Codex for starters, that's important for most things done in WP. – Rarst Oct 19 '17 at 12:23
1

This is the code that worked. Although it hooks on the_category and not on the the_category_list or get_the_categoty_list it works flawlessly.

function the_category_filter($thelist,$separator=' ') {
    if(!defined('WP_ADMIN')) {
        //list the category names to exclude
        $exclude = array('Mac','Windows');
        $cats = explode($separator,$thelist);
        $newlist = array();
        foreach($cats as $cat) {
            $catname = trim(strip_tags($cat));
            if(!in_array($catname,$exclude))
                $newlist[] = $cat;
        }
        return implode($separator,$newlist);
    } else
        return $thelist;
}
add_filter('the_category','the_category_filter',10,2);

If you want to limit this exclusion only in single posts you can enclose the code in an if statement like this:

if ( is_single() ) {
// Above code goes here
}

PS: I still wonder if there is an finer solution. For example by using something like: get_the_categories_list('exclude=1,22') in my code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.