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

放肆的年华 提交于 2019-12-06 07:55:06

问题


  • I've installed a plugin for "Gift Cards", which is basically adding a product type "Gift card".
    • I need to enhance its functionality.
    • There are other tabs available for this but the tab "Variations" is not.
    • How can i add this tab so my custom product type can also behave like a variable product.
    • Screen Shot: http://prntscr.com/ekogwd
    • And i've to use my custom product type strictly means i cannot change it to variable product type.
    • Is there any hook, action, or filter to add this tab manually to my custom product type "Gift card" using woocommerce?

回答1:


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();
        }
    });

});


来源:https://stackoverflow.com/questions/42835590/how-to-add-variations-tab-in-custom-product-type-in-woocommerce

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