You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP8.0下WooCommerce添加is_product_category()触发term_id读取错误排查

解决PHP 8.0下WooCommerce隐藏指定分类的错误问题

错误原因分析

  1. 逻辑运算符优先级错误:原代码的条件判断in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_shop() || is_product_category()中,&&优先级高于||,导致只要当前是商品分类页(is_product_category()为真),就会执行过滤逻辑,完全忽略前两个条件。这种情况下,某些场景下get_terms返回的可能是分类ID的整数数组,而非WP_Term对象数组,直接访问$term->term_id就会触发"Attempt to read property 'term_id' on int"警告。
  2. 缺少类型校验:PHP 8.0对类型严格性提升,没有判断$term是否为WP_Term对象就直接访问属性,当$term是整数时必然报错。

修复后的代码

add_filter( 'get_terms', 'sct_hide_cat', 10, 3 );

function sct_hide_cat( $terms, $taxonomies, $args ) {
    $exclude = [50, 22, 20, 31, 35, 45, 40, 65, 37, 3434]; // 去重重复的40
    $new_terms = [];

    // 修正条件括号,确保逻辑正确:仅在前台的商店页或商品分类页,且处理的是product_cat分类时才执行过滤
    if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && ( is_shop() || is_product_category() ) ) {
        foreach ( $terms as $term ) {
            // 先校验$term是否为WP_Term对象,再判断是否需要排除
            if ( $term instanceof WP_Term && ! in_array( $term->term_id, $exclude ) ) { 
                $new_terms[] = $term;
            }
        }
        $terms = $new_terms;
    }
    return $terms;
}

关键改动说明

  • 修正条件逻辑:给is_shop() || is_product_category()加上括号,确保只有在前台、处理商品分类、且当前是商店页或分类页时才执行过滤,避免错误场景触发逻辑。
  • 添加类型校验:通过$term instanceof WP_Term判断当前项是否为分类对象,只有对象才去访问term_id属性,避免对整数执行对象操作。
  • 清理冗余数据:去掉了重复的分类ID40,以及未使用的global $product变量,精简代码。

内容的提问来源于stack exchange,提问作者Naycom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:39:05