首页 > 解决方案 > 警告:sizeof():参数必须是数组或实现 Countable 的对象

问题描述

嘿朋友我需要一个解决方案来解决这个错误

警告:sizeof():参数必须是在 C:\xampp\htdocs\my-site\wp-content\themes\kingdom\woocommerce\content-single-product.php 中实现 Countable 的数组或对象,第 18 行

PHP文件行:

$cat_count = sizeof( get_the_terms( $post->ID, 'product_cat' ) );
$tag_count = sizeof( get_the_terms( $post->ID, 'product_tag' ) ); 

标签: phpwordpresswoocommerce

解决方案


如果该术语存在,则通常get_the_terms 返回任一对象,否则返回 false,这就是您出现此错误的原因。

因此,只需在您的代码中添加条件以检查是否get_the_terms为真,通过 sizeof 在变量中添加 if not just return 0 来计算条款:

$cat_count = (get_the_terms($post->ID, 'product_cat')) ? sizeof(get_the_terms($post->ID, 'product_cat')) : 0;
$tag_count = (get_the_terms($post->ID, 'product_tag')) ? sizeof(get_the_terms($post->ID, 'product_tag')) : 0;

代码参考


推荐阅读