如何在WooCommerce中设置选项卡(仅当产品属于特定类别时)

4
我有一个选项卡设置,用于在WooCommerce中添加包含规格的选项卡。我希望将其包装成一个if语句,以仅在产品属于特定类别时设置选项卡。
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );

function woo_custom_product_tabs( $tabs ) {

    global $post;

    if ($product->is_category("Mobile Phones")) { 
        $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
    }
}

如何正确地在if语句中检查WooCommerce类别的代码?


我没有忘记,只是为了节省空间,没有添加。我在发布问题后的大约十分钟内解决了这个问题,并将答案上传。 - mitchelangelo
是的,你的结论和我的差不多,只是我使用了if ($product->is_type( 'grouped' ) && has_term( 'SIM Cards', 'product_cat' ) || has_term( 'SIM Cards', 'product_cat' ) ) - mitchelangelo
显然,在声明$product = get_product( $post->ID );之后。 - mitchelangelo
我有类似于移动电话的代码,我的问题是如何检查产品类别,上面只是我用SIM卡做的同样的事情的示例。 - mitchelangelo
"has_term"就是我正在寻找的,谢谢。 - mitchelangelo
2个回答

3

条件语句is_category()会在您访问分类归档页面时返回true。

由于您需要针对单个产品页面进行条件判断,因此可以通过以下方式结合使用is_product()条件来定位单个产品页面:

if ( is_product() && has_term( 'Mobile Phones', 'product_cat' ) ) {
    $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}

或者,如果有需要,您也可以尝试这个:

if( is_product() && has_category( 'Mobile Phones' ) ) {
    $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
}

@edit: 在你的函数中,最后一个闭合括号}之前,你遗漏了return $tabs;


参考资料:


2
尝试下面的代码。当产品具有 "Mobile Phones" 类别时,此代码仅添加 WooCommerce 选项卡。
add_filter( 'woocommerce_product_tabs', 'woo_custom_product_tabs' );

    function woo_custom_product_tabs( $tabs ) {

      global $post;
     if ( is_product() && has_term( 'Mobile Phones', 'product_cat' )) 
     { 
      $tabs['custom_specification'] = array( 'title' => __( 'Specification', 'woocommerce' ), 'priority' => 50, 'callback' => 'woo_custom_specification_content' );
      }
      return $tabs;
    }

请不要抄袭我的答案,谢谢! - LoicTheAztec
我纠正了问题代码并添加了解决方案。问题代码中缺少了"return $tabs;"这一行。 - pallavi
是的,但你只是复制了我的条件语句...所以请避免这样做...谢谢。OP的问题与条件语句有关。return $tabs;只是OP疏忽了。你可以在OP的问题中添加一条注释来说明这一点... - LoicTheAztec

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接