How to use if statement to display taxonomy name if in the taxonomy

I’m using the code below to get the name and slug of a custom taxonomy and than in the loop I echo the taxonomy name but not every post is linked to this taxonomy and if the post is not linked to the taxonomy get the error

Invalid argument supplied for foreach()

Read More

So I was wondering how do I use an if statement so if the post is not in the taxonomy than nothing happens. I tried wrapping the code below in a if(is_tax statement when I did that the custom taxonomy name didn’t display on any of the posts.

<?php 
        $terms = get_the_terms($post->ID, 'class-content' );
        foreach ( $terms as $term ) {
            $class_name = $term->name; // this grabs the hyphenated name
            $class_slug = $term->slug; // this grabs the hyphenated slug
        }

?>

Related posts

Leave a Reply

1 comment

  1. $terms = get_the_terms($post->ID, 'class-content' );
    if(is_object($terms)){
            foreach ( $terms as $term ) {
                $class_name = $term->name; // this grabs the hyphenated name
                $class_slug = $term->slug; // this grabs the hyphenated slug
            }
    }