首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP: count():参数必须是实现可数的数组或对象

PHP: count():参数必须是实现可数的数组或对象
EN

Stack Overflow用户
提问于 2022-07-19 02:30:46
回答 4查看 95关注 0票数 0

我对php很陌生。我在一些Wordpress页面上出现了这些错误。

警告: count():参数必须是在第38行的/www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php中实现可数的数组或对象

警告:为第40行的/www/tastingvictoria_289/public/wp-content/themes/astra-child/template-parts/content-single.php中的foreach()提供的无效参数

这是相关代码。

代码语言:javascript
复制
<?php $terms = get_the_terms( $post->ID , 'category' ); 
        $total = count($terms); // 38
        $i=0;
        foreach ( $terms as $term ) {
            if($term->slug != "featured-post"){
                $i++;
                $term_link = get_term_link( $term, 'category' );
                if( is_wp_error( $term_link ) )
                continue;
                echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
                if ($i != $total) echo ' ';
            }
            
        } 
        ?>

有什么解释吗?

EN

回答 4

Stack Overflow用户

发布于 2022-07-19 03:36:27

作为错误消息,传递到count()函数的$term参数而不是可数(在某些情况下,post id不是退出)。

若要解决此问题,请将代码更改为:

代码语言:javascript
复制
<?php $terms = get_the_terms( $post->ID , 'category' );
if(is_array($terms)){
    $total = count($terms); // 38
    $i=0;
    foreach ( $terms as $term ) {
        if($term->slug != "featured-post"){
            $i++;
            $term_link = get_term_link( $term, 'category' );
            if( is_wp_error( $term_link ) )
            continue;
            echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
            if ($i != $total) echo ' ';
        }
        
    }
  }
?>
票数 0
EN

Stack Overflow用户

发布于 2022-07-19 04:01:19

$terms转换为数组以获得count($terms)的有效结果。

票数 0
EN

Stack Overflow用户

发布于 2022-07-19 06:08:37

get_the_terms() 在成功时返回WP_Term对象的数组,如果没有条件或不存在post,则返回WP_Error失败。

可能是不存在的条件。尝试以下几个方面:

代码语言:javascript
复制
$terms = get_the_terms( $post->ID , 'category' );

if ( $terms && ! is_wp_error( $terms ) ) : 
$total = count($terms);
$i=0;
foreach ( $terms as $term ) {
    if($term->slug != "featured-post"){
        $i++;
        $term_link = get_term_link( $term, 'category' );
        if( is_wp_error( $term_link ) )
        continue;
        echo '<p class="category"><span><a class="" href="' . $term_link . '">' . $term->name . '</a></span></p>';
        if ($i != $total) echo ' ';
    }
    
}
endif;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73030485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档