Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • 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?
like image 918
Esar-ul-haq Qasmi Avatar asked Mar 09 '23 14:03

Esar-ul-haq Qasmi


1 Answers

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

});
like image 99
helgatheviking Avatar answered Apr 07 '23 00:04

helgatheviking