Exclude a category from the filed under list only on some templates

this is a follow up question to this post Exclude a category from the filed under list

The solution given works for me. However, I’m curious how I can get this to work conditionally? Specifically, only on category archives? E.g. It will still say “Filed Under: A, B, X” on single post templates. But it will say “Filed Under: A, B” on archives.

Working in Genesis, if that helps.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can add conditional statements before applying the logic to modify the categories. For example, I added a check that will bail and return the unmodified list of categories if we’re not on the category archive page:

// Add the filter to 'the_category' tag.
add_filter( 'the_category', 'the_category_filter', 10, 2 );
function the_category_filter( $thelist, $separator = ' ' ) {

    // Bail if this is not the category archive page.
    // https://developer.wordpress.org/reference/functions/is_tax/
    if ( ! is_tax( 'category' ) ) {
        return $thelist;
    }

    // list the IDs of the categories to exclude
    $exclude = array(4,5);
    // create an empty array
    $exclude2 = array();

    // loop through the excluded IDs and get their actual names
    foreach($exclude as $c) {
             // store the names in the second array
             $exclude2[] = get_cat_name($c);
    }

    // get the list of categories for the current post
    $cats = explode($separator,$thelist);
    // create another empty array
    $newlist = array();

    foreach($cats as $cat) {
        // remove the tags from each category
        $catname = trim(strip_tags($cat));

        // check against the excluded categories
        if(!in_array($catname,$exclude2))

        // if not in that list, add to the new array
        $newlist[] = $cat;
    }

    // return the new, shortened list
    return implode( $separator, $newlist );
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x