在以下两个函数中,您需要先设置父变量产品 ID,然后在第一个函数上设置每个变体 ID 以及对应的固定数量。
要根据每个选择的变化动态设置输入数量,唯一的方法是使用 Javascript (Jquery)。这是在第二个函数中完成的。
代码:
add_filter( 'woocommerce_available_variation', 'custom_variation_min_max_qty', 10, 3 );
function custom_variation_min_max_qty( $data, $product, $variation ) {
// Your variable product ID
$variable_id = 73;
if( $product->get_id() == $variable_id ) {
// Set 1st variation ID
if( $variation->get_id() == 1015 ){
$qty = 3; // Set the quantity
}
// Set 2nd variation ID
elseif( $variation->get_id() == 1014 ){
$qty = 6; // Set the quantity
}
// Set 3rd variation ID
elseif( $variation->get_id() == 1013 ){
$qty = 12; // Set the quantity
}
}
if( isset($qty) ) {
$data['min_qty'] = $qty;
$data['max_qty'] = $qty;
}
return $data;
}
add_action( 'woocommerce_after_single_variation', 'change_variation_input_quantity_script' );
function change_variation_input_quantity_script() {
global $product;
// Your variable product ID
$variable_id = 73;
if( $product->get_id() != $variable_id ) return;
// Output Javascript
?>
<!-- JS Thankyou Script -->
<script type="text/javascript">
jQuery(function($) {
var a = 'div.quantity > input.qty';
// On load
setTimeout(function(){
$(a).val($(a).prop('min'));
}, 300);
// On change / select a variation
$('.variations_form select').on( 'blur', function(){
if( $('input[name="variation_id"]').val() > 0 )
$(a).val($(a).prop('min'));
})
});
</script>
<?php
}
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。
可以根据特定的产品属性值自动进行正确的变异检测...
就像在您的示例中一样,这可以通过针对变体的颜色产品属性值来完成。您需要在函数中定义“颜色”产品属性分类,即 pa_color。
所以你将用这个替换第一个函数:
add_filter( 'woocommerce_available_variation', 'custom_variation_min_max_qty', 10, 3 );
function custom_variation_min_max_qty( $data, $product, $variation ) {
// Your variable product ID
$variable_id = 73;
if( $product->get_id() == $variable_id ) {
// Define your product attribute (always start with "pa_" + the slug)
$taxonomy = 'pa_color';
foreach($data['attributes'] as $attribute => $value_slug ){
if( $attribute == 'attribute_' . $taxonomy ) {
// set your color slugs below with the correct quantity
if ( $value_slug == 'red' )
{
$qty = 3; // Set the quantity for "Red" color
break;
}
elseif ( $value_slug == 'blue' )
{
$qty = 6; // Set the quantity for "Blue" color
break;
}
elseif ( $value_slug == 'green' )
{
$qty = 12; // Set the quantity for "Green" color
break;
}
}
}
}
if( isset($qty) ) {
$data['min_qty'] = $qty;
$data['max_qty'] = $qty;
}
return $data;
}
您将保持第二个功能不变。
代码进入您的活动子主题(或活动主题)的 function.php 文件中。经过测试并且可以工作。