如何修复WordPress中get_the_terms()引发的foreach()参数类型警告?
修复WooCommerce产品标签云的foreach警告问题
问题原因
你遇到的Warning: foreach() argument must be of type array|object, bool警告,是因为代码中get_the_terms( $product->get_id(), 'product_tag' )这个调用:当产品没有关联任何产品标签,或者查询过程出现错误时,该函数会返回false(甚至是WP_Error对象),而foreach只能遍历数组或对象,直接遍历布尔值就会触发警告。
修复方案
在遍历$tags之前,先判断它是否为有效可遍历的类型,同时排除错误对象。具体要在foreach ($tags as $tag)前添加判断条件:
if ( $tags && ! is_wp_error( $tags ) ) { foreach ($tags as $tag) { // 原有的标签处理代码 } }
修改后的完整代码
function custom_product_tag_cloud_func() { if (is_shop()) { $args= array( 'smallest' => 13, 'largest' => 13, 'taxonomy' => 'product_tag', 'unit' => 'px', 'number' => 10, 'format' => 'flat', 'separator' => " ", 'orderby' => 'count', 'order' => 'DESC', 'show_count' => 0, 'number' => 0, ); echo'<div class="widget_product_tag_cloud"><span class="gamma widget-title"></span><div class="tagcloud"><ul class="wp-tag-cloud">'; wp_tag_cloud($args); echo '</ul></div></div>'; } global $wp; $current_slug = add_query_arg( array(), $wp->request ); if(strpos($current_slug, '/') !== false) { $newtest = explode('/', $current_slug); $current_slug = array_pop($newtest); } $args = array( 'category' => array( $current_slug ), 'limit' => -1, ); $products = wc_get_products( $args ); $tags_objects = array(); foreach ($products as $product) { $tags = get_the_terms( $product->get_id(), 'product_tag' ); // 添加判断,确保$tags是有效可遍历的类型 if ( $tags && ! is_wp_error( $tags ) ) { foreach ($tags as $tag) { $slug = $tag->slug; $cat_slug = add_query_arg( array(), $wp->request ); $tag->link = get_term_link( $tag ); //get_site_url()."/".$cat_slug."?product_tag=".$slug; array_push($tags_objects,$tag); } } } $tags_objects = array_unique($tags_objects, SORT_REGULAR); $args = array( 'smallest' => 13, 'largest' => 13, 'number' => 10, 'format' => 'flat', 'separator' => " ", 'orderby' => 'count', 'order' => 'DESC', 'unit' => 'px', 'show_count' => 0, 'number' => 0, ); $tag_cloud = wp_generate_tag_cloud($tags_objects,$args); if(is_product_category()){ echo'<div class="widget_product_tag_cloud"><span class="gamma widget-title"></span><div class="tagcloud"><ul class="wp-tag-cloud">'; echo $tag_cloud; echo '</ul></div></div>'; } }
内容的提问来源于stack exchange,提问作者Lgane
相关产品推荐
相关产品推荐

