警告:sizeof():参数必须是实现 Countable 的数组或对象



嘿朋友们,我需要一个解决方案来修复此错误

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

PHP文件的行:

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

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

因此,只需在代码中添加条件以检查get_the_terms是否为真,请通过添加sizeof来计算项,如果不是仅在变量中返回 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;

代码参考

你应该使用wp_count_terms,因为看起来你只需要这里的计数

https://developer.wordpress.org/reference/functions/wp_count_terms/

相关内容

最新更新