Question

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()

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
        }

?>
Was it helpful?

Solution

$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
        }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top