Nuc
Nuc

Reputation: 33

WooCommerce show "used for variations" tickbox (custom product type)

I have created a Custom Variable Product Type named vp_extended. By default the tickbox "Used for variations" is not showing under attributes when I added a attribute named "Size". So when I added below code:

<?php
function producttype_custom_js() {

    if ( 'product' != get_post_type() ) :
        return;
    endif;
?>
   <script type='text/javascript'>
       jQuery( document ).ready( function($) {

            $('.enable_variation').addClass('show_if_vp_extended').show();

      });
   </script>
<?php 
} 
add_action( 'admin_footer', 'producttype_custom_js' );  

The tickbox is showing and I can use it. The problem is that when I choose to add another attribute (ex. Gender) the page is loading for a bit then both attributes is missing the tickbox "used for variations".

When I inspect the element in CSS, I can see that my class "show_if_vp_extended" is added to the ".enable_variation" class on the first element and style says display = block (all good here). But when I add the second attribute to the product it will not get my class and the first element change CSS to "display: none" but still having my vp-extended class.

What do I miss or do wrong here?

Picture when JavaScript function works on 1 attribute: Picture when JavaScript function works on 1 attribute

Picture when choosing to add 1 more attribute: Picture when choosing to add 1 more attribute...

Upvotes: 1

Views: 1362

Answers (1)

helgatheviking
helgatheviking

Reputation: 26309

The newly added attribute isn't in the DOM so your code will not effect it. I believe you need to run your code every time an attribute is added.

Something like this might work:

$( 'body' ).on( 'woocommerce_added_attribute', function( event ){
    $('.woocommerce_attribute_data .enable_variation').addClass('show_if_vp_extended').show();
});

Or borrowing heavily from Subscriptions, this might be more complete:

$('body').on('woocommerce_added_attribute', function(){
    if ($('select#product-type').val()=='vp_extended') {

        $( 'input#_downloadable' ).prop( 'checked', false );
        $( 'input#_virtual' ).removeAttr( 'checked' );

        $('.show_if_variable').show();
        $('.hide_if_variable').hide();
        $('.show_if_vp_extended').show();
        $('.hide_if_vp_extended').hide();
        $( 'input#_manage_stock' ).change();

    }
});

Upvotes: 2

Related Questions