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

升级至WordPress 6.0后WooCommerce has_term函数失效的排查与替代方案咨询

解决WordPress 6.0后WooCommerce中has_term失效的问题

首先得搞清楚核心问题:loop_shop_columns这个钩子的执行时机,在商品分类存档页面(非主商城页)触发时,全局的$post对象还没初始化到单个商品上,has_term默认会检查当前$post,自然返回false。而WordPress 6.0可能调整了钩子执行时机,让之前偶然生效的逻辑彻底失效了,而且因为这是逻辑判断问题而非语法错误,所以debug.log不会记录报错。

下面分调试方法和替代方案来帮你解决:

一、调试步骤(定位问题根源)

  • 检查当前上下文对象:在你的函数里临时加入调试代码,看看当前页面的查询对象是什么:

    function lw_loop_shop_columns( $columns ) {
        // 临时调试:把当前查询对象输出到debug.log
        error_log('当前查询对象详情:' . print_r(get_queried_object(), true));
        error_log('has_term默认返回值:' . has_term( array ( 'cursos', 'courses', 'talleres', 'workshops', 'safaris-fotograficos', 'photo-safaris', 'turismo-alternativo', 'alternative-tourism', 'servicios', 'services', 'software', 'software-en', 'aventuras-fotograficas', 'photo-adventures' ), 'product_cat' ));
        
        // 原逻辑代码
        if ( !is_shop() && has_term( array ( 'cursos', 'courses', 'talleres', 'workshops', 'safaris-fotograficos', 'photo-safaris', 'turismo-alternativo', 'alternative-tourism', 'servicios', 'services', 'software', 'software-en', 'aventuras-fotograficas', 'photo-adventures' ), 'product_cat' ) ) {
            $columns = 2;
        } else {
            $columns = 3;
        }
        return $columns;
    }
    

    打开wp-content/debug.log你会发现,当前查询对象是WP_Term(分类对象),不是单个商品,这就是has_term失效的核心原因——它找不到要检查的商品主体。

  • 手动传入测试对象验证:尝试给has_term传入当前分类的ID,看看返回结果:

    $current_term = get_queried_object();
    error_log('传入分类ID后的has_term返回值:' . has_term( array ( 'cursos', 'courses', ... ), 'product_cat', $current_term ));
    

    这时候会返回true,但这个逻辑其实不对——has_term是用来检查帖子(商品)是否属于某个分类,而非分类是否属于某个分类。

二、替代方案(正确的逻辑实现)

你的需求是在指定商品分类的存档页,将商品列数改为2列,完全不需要用has_term,直接用WooCommerce专门提供的is_product_category()函数更准确,它就是用来判断当前是否是某商品分类的存档页:

修改后的代码如下:

add_filter( 'loop_shop_columns', 'lw_loop_shop_columns' );
function lw_loop_shop_columns( $columns ) {
    $target_categories = array( 
        'cursos', 'courses', 'talleres', 'workshops', 
        'safaris-fotograficos', 'photo-safaris', 
        'turismo-alternativo', 'alternative-tourism', 
        'servicios', 'services', 'software', 'software-en', 
        'aventuras-fotograficas', 'photo-adventures' 
    );
    
    // 检查当前是否是指定商品分类存档页,且不是主商城页
    if ( !is_shop() && is_product_category( $target_categories ) ) {
        $columns = 2;
    } else {
        $columns = 3;
    }
    return $columns;
}

额外补充

如果之后你需要在单个商品上下文(比如商品详情页、商品循环内)检查分类,has_term依然可用,但要确保传入正确的商品对象/ID:

// 示例:在商品循环内使用
if ( has_term( $target_categories, 'product_cat', get_the_ID() ) ) {
    // 你的逻辑代码
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 22:22:29