首页 文章

如果在分类法中如何使用if语句来显示分类法名称

提问于
浏览
1

我正在使用下面的代码来获取自定义分类法的名称和slug,而不是在循环中我回应分类法名称但不是每个帖子都链接到此分类法,如果帖子没有链接到分类法,则得到错误

为foreach()提供的参数无效

所以我想知道如何使用if语句,所以如果帖子不在分类中而不是没有发生 . 我尝试将下面的代码包装在if(is_tax语句中),当我这样做时,自定义分类名称没有显示在任何帖子上 .

<?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
        }

?>

1 回答

  • 2
    $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
            }
    }
    

相关问题