Last active
April 23, 2021 09:17
-
-
Save damiencarbery/6d1297fd0c605da6cbfa460b8f3ab4aa to your computer and use it in GitHub Desktop.
Multiple required fields in WooCommerce - Enhance last year's code to make multiple WooCommerce product fields required. https://www.damiencarbery.com/2019/09/multiple-required-fields-in-woocommerce/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: Multiple Required fields (WooCommerce) | |
Plugin URI: https://www.damiencarbery.com/2019/09/multiple-required-fields-in-woocommerce/ | |
Description: Enhance last year's code to make multiple WooCommerce product fields required. | |
Author: Damien Carbery | |
Author URI: http://www.damiencarbery.com | |
Version: 0.2 | |
WC tested up to: 5.2.2 | |
*/ | |
add_action( 'admin_head', 'dcwd_require_weight_field' ); | |
function dcwd_require_weight_field() { | |
$screen = get_current_screen(); | |
$screen_id = $screen ? $screen->id : ''; | |
if ( $screen_id == 'product' ) { | |
?> | |
<script> | |
jQuery(document).ready(function($){ | |
required_fields_data = [ | |
[ 'Weight', '#_weight', 'Shipping', '.shipping_tab > a' ], | |
[ 'Length', '#product_length', 'Shipping', '.shipping_tab > a' ], | |
[ 'Width', '#product_width', 'Shipping', '.shipping_tab > a' ], | |
[ 'Height', '#product_height', 'Shipping', '.shipping_tab > a' ], | |
]; | |
num_required_fields = required_fields_data.length; | |
// Set the fields as required. | |
for ( i = 0; i < num_required_fields; i++ ) { | |
$( required_fields_data[ i ][ 1 ] ).prop('required',true); | |
} | |
// Verify that each required field has a non-zero value before allowing save. | |
$( '#publish' ).on( 'click', function() { | |
error_message = ''; | |
target_field = null; | |
target_tab = null; | |
for ( i = 0; i < num_required_fields; i++ ) { | |
value = $.trim($( required_fields_data[ i ][ 1 ] ).val()); | |
if ( value == '' || value == 0 ) { | |
error_message += required_fields_data[ i ][ 0 ] + " must be set in the "+ required_fields_data[ i ][ 2 ] +" tab.\n"; | |
target_field = required_fields_data[ i ][ 1 ]; | |
target_tab = required_fields_data[ i ][ 3 ]; | |
} | |
} | |
if ( error_message != '' ) { | |
alert( error_message ); | |
$( target_tab ).click(); // Click on appropriate tab. | |
$( target_field ).focus(); // Focus on the appropriate field. | |
return false; | |
} | |
}); | |
}); | |
</script> | |
<?php | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment