How to add Variations tab in custom product type in Woocommerce?

白昼怎懂夜的黑 提交于 2019-12-04 14:45:57

I assume you've already added the Gift Card to the product type selector. However, I'm adding it here for completeness and because you ave to use the same name in the second function.

add_filter( 'product_type_selector', 'so_42835590_add_product_type' );
function so_42835590_add_product_type( $types ){

    // Key should be exactly the same as in the class product_type parameter
    $types[ 'gift-card' ] = __( 'Gift Card', 'your-plugin' );

    return $types;

}

You can add your own custom tabs by filtering woocommerce_product_data_tabs but you can also add classes to the existing tabs. Classes are what the metabox javascript uses to decide what to show and what to hide when the product type is changed.

add_filter( 'woocommerce_product_data_tabs', 'so_42835590_product_data_tabs' );
function so_42835590_product_data_tabs( $tabs ) {

    $product_type = 'gift-card'; // must match array key in previous snippet

    // Add an additional class to an existing tab, ex: Variations.
    $tabs[ 'variations' ][ 'class' ][] = 'show_if_' . $product_type;  

    return $tabs;
}

Edit you do need to add some javascript to control the visibility of "Enabled for variations" tab in existing attributes, and when attributes are added. This should do the trick:

jQuery( function ( $ ) {

    // Variable type options are valid for variable workshop.
    $( '.show_if_variable:not(.hide_if_gift-card)' ).addClass( 'show_if_gift-card' );

    // Trigger change
    $( 'select#product-type' ).change();

    // Show variable type options when new attribute is added.
    $( document.body ).on( 'woocommerce_added_attribute', function(e) {

        $( '#product_attributes .show_if_variable:not(.hide_if_gift-card)' ).addClass( 'show_if_gift-card' );

        var $attributes     = $( '#product_attributes' ).find( '.woocommerce_attribute' );

        if ( 'gift-card' == $( 'select#product-type' ).val() ) {
            $attributes.find( '.enable_variation' ).show();
        }
    });

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!