How to exclude specific category from the get_the_category(); array

In my loop I’ve added:

<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
if($categories){
    foreach($categories as $category) {
        $output .= '<span class="post-category-info"><a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a></span>'.$separator;
    }
echo trim($output, $separator);
}
?>

to display all the categories attached to the post here.

Read More

There is a specific category “Featured” that I want to prevent from displaying.

I’ve tried :

<?php
$categories = get_the_category();
$separator = ' ';
$output = '';
if($categories){
    foreach($categories as $category) {
if($category !== 'Featured'){
        $output .= '<span class="post-category-info"><a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a></span>'.$separator;}
    }
echo trim($output, $separator);
}
?>

But I guess it’s a wrong approach since it’s not working 🙂

Can anyone please help to achieve my task or at least point me in the right direction? 🙂

Related posts

2 comments

  1. $category is an object containing member variables, you have to check the specific member var you want to compare.

    change:

    if($category !== 'Featured')
    

    to:

    if($category->name !== 'Featured')
    
  2. To take this a step further, if you wanted to exclude multiple categories try the following…

        <?php
    $categories = get_the_category();
    $separator = ' ';
    $output = '';
    if($categories){
        foreach($categories as $category) {
    if($category->name !== 'category name 1') 
    if($category->name !== 'category name 2')
    if($category->name !== 'category name 3')
    {
            $output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator; }
        }
    echo trim($output, $separator);
    }
    ?>
    

Comments are closed.