문제

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
        }

?>
도움이 되었습니까?

해결책

$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
        }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top