Site logo

Archived topic

Hide specific categories on front and archive pages in post meta

18 replies · Started by Tobias on March 22, 2021

Viewing posts 16–19 of 19

i corrected your code, that it works without error, but it is not the right result.

add_filter('pre_get_posts', 'excludeCat');
function excludeCat($query) {
if ( $query->is_home() || $query->is_archive() || $query->is_search() ) {
$query->set('cat', '-31');
}
return $query;
}

pre_get_posts will exclude the actual posts from the page - not the meta items. Are you wanting to exclude the entire posts with that category, or only the name of the category from the list of categories in the post meta?

Hey Tom,

I wish to only hide the name of the category from the post meta.

Thanks and best regards!

Ah so you mean you just want to remove specific categories?

If that's the case, we can filter the get_the_category_list the theme uses to display its category terms.

You can try this PHP snippet:

function the_category_filter($thelist,$separator=' ') {
    if(!defined('WP_ADMIN')) {
        //Category IDs to exclude
        $exclude = array(32,33);
        
        $exclude2 = array();
        foreach($exclude as $c) {
            $exclude2[] = get_cat_name($c);
        }
        
        $cats = explode($separator,$thelist);
        $newlist = array();
        foreach($cats as $cat) {
            $catname = trim(strip_tags($cat));
            if(!in_array($catname,$exclude2))
                $newlist[] = $cat;
        }
        return implode($separator,$newlist);
    } else {
        return $thelist;
    }
}
add_filter('the_category','the_category_filter', 10, 2);

To exclude a specific category, you can specify it on this line:

$exclude = array(32,33); change 32 and 33 to the category IDs you want to exclude on the post meta.

This archived topic is closed to new replies.