【问题标题】:Trying to update to PHP 7.4 but getting this error in an element, Warning: count(): Parameter must be an array or an object that implements Countable尝试更新到 PHP 7.4 但在元素中出现此错误,警告:count(): Parameter must be an array or an object that implements Countable
【发布时间】:2022-01-10 14:36:49
【问题描述】:

嘿,我是新来的,听说了很多关于这个有用社区的信息。我正在尝试将我的自定义构建主题更新为 PHP 7.4,但在兼容性测试期间我发现了这个错误,我们将不胜感激。

我对 PHP 的了解为 0(目前)

这里是代码。

$type_terms = get_the_terms( $post->ID,"property-type" );
$type_count = count($type_terms);
if(!empty($type_terms)){
    echo '<small> - ';
    $loop_count = 1;
    foreach($type_terms as $typ_trm){
        echo $typ_trm->name;
        if($loop_count < $type_count && $type_count > 1){
            echo ', ';
        }
        $loop_count++;
    }
    echo '</small>';
}else{
    echo '&nbsp;';
}
?>
            </span>
        </h5>
    </div>

    <div class="property-meta clearfix">
        <?php

谢谢

【问题讨论】:

  • 这意味着get_the_terms 返回了一个不是数组的值(例如NULLfalse,或字符串)。可能,将$type_count = count($type_terms); 移到下面一行(if 下)可以解决问题
  • 在这种情况下 $post 是什么?你得到什么?
  • 使用var_dump($some-variable); 可能有助于调试。
  • 谢谢大家从这里学到了很多关于 get_the_terms 的知识!问题已解决,感谢大家参与提问!

标签: php wordpress wordpress-theming php-7.3


【解决方案1】:

来自 WordPress documentation 关于get_the_terms

返回:成功时WP_Term对象数组,false,如果没有term或post不存在,失败时WP_Error。

这意味着get_the_terms 函数将返回这三个选项中的一个:

  1. 错误
  2. 数组

如果帖子有一些“条款”,那么您将不会收到任何警告,但是当您尝试计算一些不是有效数组(或任何可数对象)的结果时会发生这种情况。 这样您就可以在尝试计算获取的术语之前对其进行检查:

if(is_array($type_terms))
   $type_count = count($type_terms);
else 
   $type_count = [];

或三元运算:

$type_count = is_array($type_terms) ? count($type_terms); : [] ;

【讨论】:

  • 谢谢它的工作:)
猜你喜欢
  • 2023-01-26
  • 2020-11-02
  • 2018-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 2020-08-07
  • 2013-07-25
相关资源
最近更新 更多