How do I prefill the price field in the woo-commerce edit product page?
The price fields, I want to prefill are (Minimum) & (Maximum) price fields. These fields are generated by the "Name your price" plugin from WooCommerce.
The label for minimum price is _min_price
The label for the maximum price is _maximum_price
I want the "Minimum Price" field to be prefilled with "10" & the "Maximum Price" field should be "250"
I've tried using the following code, but it didn't work.
add_action( 'woocommerce_product_options_general_product_data',
'prefill_min_max' );
function prefill_min_max(){
?>
<script>
(function($){
$('input[name=_min_price]').val('10');
$('input[name=_maximum_price]').val('250');
})(jQuery);
</script>
<?php
}
CodePudding user response:
Your code needs improvement and fixes, here is the fixed and updated code.
/**
* Hook script in admin footer.
*/
add_action(
'admin_footer',
function () {
// Get the current screen ID.
$screen = get_current_screen();
$screed_id = $screen->id ? $screen->id : '';
// We only want to load our script on the product edit page screen.
if ( ! in_array( $screed_id, array( 'product' ), true ) ) {
return;
}
?>
<script>
(function ($) {
// Get the minimum price element.
$min_price = $(".product_data input[name=_min_price]");
// Check if the element exists and is empty. don't wanna make the change on an already filled value.
if ($min_price.length && $min_price.val() === "") {
$min_price.val(10);
}
// Get the maximum price element.
$maximum_price = $(".product_data input[name=_maximum_price]");
// Check if the element exists and is empty. don't wanna make the change on an already filled value.
if ($maximum_price.length && $maximum_price.val() === "") {
$maximum_price.val(250);
}
})(jQuery);
</script>
<?php
}
);