在WooCommerce中将自定义标签添加到特定产品类型的单个产品页面

时间:2020-10-15 08:57:51

标签: php wordpress woocommerce tabs product

基于此代码,我想为WooCommerce 4.4.1 中的可变产品创建自定义标签。

但是不幸的是,此自定义选项卡已添加到所有产品类型中,是否可以解决此问题?

如果我错了,请纠正我。

add_filter( 'woocommerce_product_tabs', 'woo_new_product_tab' );
function woo_new_product_tab( $tabs ) {
    
    // Adds the new tab for variable product type
    global $product;
 
    if( $product->is_type( 'variable' ) ) {
        
        $tabs['test_tab'] = array(
            'title'     => 'features',
            'priority'  => 50,
            'class'     => array('general_tab', 'show_if_variable'),
            'callback'  => 'woo_new_product_tab_content'
        );
    }

    return $tabs;
}

1 个答案:

答案 0 :(得分:1)

要查找错误,您可以执行一些额外的检查并打印产品类型。 测试后可以删除else条件。

function filter_woocommerce_product_tabs( $tabs ) {
    // Get the global product object
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get type
        $product_type = $product->get_type();
        
        // Compare
        if ( $product_type == 'variable' ) {        
            $tabs['test_tab'] = array(
                'title'     => 'features',
                'priority'  => 50,
                'callback'  => 'woo_new_product_tab_content'
            );
        } else {
            echo 'DEBUG: ' . $product_type;
        }
    } else {
        echo 'NOT a WC product';
    }

    return $tabs;
}
add_filter( 'woocommerce_product_tabs', 'filter_woocommerce_product_tabs', 10, 1 );

// Callback
function woo_new_product_tab_content() {
    // The new tab content
    echo '<h2>New Product Tab</h2>';
    echo '<p>Here\'s your new product tab.</p>';
}