WooCommerce product variations: Auto enable Manage Stock and set stock quantity

Viewed 990

On Admin Woocommerce product pages, for variable products, on "Variations" settings, for all product variations, I would like to have Manage Stock option enabled by default with the Stock Quantity option set to 1.

Using Get Woocommerce to Manage Stock as a default answer code, I am able to do it for the default inventory tab (for the parent variable product).

I even tried Woocommerce: Creating variations - Manage stock checked by default answer code, but it didn't worked form me.

Any help will be appreciated.

2 Answers

For info, woocommerce_product_variation_get_manage_stock hook doesn't exist anymore.

Based on jQuery code, the following will enable Manage Stock and will set Stock Quantity to 1, for all product variations:

add_action( 'admin_footer', 'custom_admin_product_variations_js' );
function custom_admin_product_variations_js() {
    global $post_type;

    if ( 'product' === $post_type ) :
    ?><script type='text/javascript'>
    jQuery( function($) {
        $('#variable_product_options').on( 'change', function(){
            $('input.variable_manage_stock').each( function(){
                if( ! $(this).is(':checked') ){
                    $(this).attr('checked', 'checked').closest('div').find('.wc_input_stock').val(1);
                }
            });
        });
    });
    </script><?php
    endif;
}

Code goes in functions.php file of the active child theme (or active theme). Tested and works.

In case if you only want to checked, variation manage stock and do not want to change stock quantity, similarly if you want that it should be edited on variation level in case product level manage stock is no checked

Following is the code (Edited version of above posted answer by @LoicTheAztec )

/* Manage Stock Checked By Default On New Product */
if (jQuery("body").hasClass("post-new-php") && jQuery("body").hasClass("post-type-product")) {
 //By default check product level manage stock  
 jQuery("#_manage_stock").prop('checked',true);

 jQuery('#variable_product_options').on( 'change', function(){
    //condition in case product level manage stock is checked 
   if(jQuery("#_manage_stock").prop('checked') == true){
        jQuery('input.variable_manage_stock').each( function(){
            if( ! jQuery(this).is(':checked') ){
                jQuery(this).attr('checked', 'checked');
            }
        });
      }
  });
}
/* END:: Manage Stock Checked By Default On New Product */
Related