如果产品属于特定类别 WooCommerce,我如何设置选项卡(仅)

How can I set tab (only) if the product is in a certain category WooCommerce

我有一个选项卡集来添加一个包含 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 类别的正确代码是什么?

条件 is_category() 如果您在类别存档页面上,则 return 为真。

由于您需要单个产品页面的条件,因此您将以 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: 你在最后一个右括号 }[=36 之前的函数末尾错过了 return $tabs; =].


参考文献:

试试下面的代码。此代码仅在产品具有 手机 类别时添加 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;
    }