您可以使用以下代码在所选差异价格旁边显示此‘Variant_Group_of_Quantity’自定义字段,而不是使用短代码(您将永远无法获得所选差异ID):
add_action( 'woocommerce_available_variation', 'product_variation_group_of_quantity', 10, 3 );
function product_variation_group_of_quantity( $variation_data, $product, $variation ) {
// Adding to the main product form the group of quantity custom field (for each variation)
$variation_data['group_of_quantity'] = $variation->get_meta('variation_group_of_quantity');
if ( $variation_data['group_of_quantity'] ) {
// Adding "Group of quantity html to the formatted price html
$variation_data['price_html'] .= sprintf(
'<span id="group-of-quantity">%s %s</span>',
__('Grouped by quantity of', 'woocommerce'),
$variation_data['group_of_quantity']
);
}
return $variation_data;
}
代码放在活动子主题(或活动主题)的函数.php文件中.经过测试,效果良好.
您将得到如下内容:
加法
现在您也只能使用以下功能,这将添加到每个变化的主要产品您的"按数量分组"自定义域.
这将允许您使用一些JavaScript(JQuery)在您喜欢的地方显示所选变体的这个定制字段值.
在下面的示例中,自定义字段Text+Value将显示在产品元部分中(SKU之后).
Php代码:
add_action( 'woocommerce_available_variation', 'product_variation_group_of_quantity', 10, 3 );
function product_variation_group_of_quantity( $variation_data, $product, $variation ) {
// Adding to the main product form the group of quantity custom field (for each variation)
$variation_data['grouped_quantity'] = $variation->get_meta('variation_group_of_quantity');
return $variation_data;
}
Java代码示例(嵌入了PHP):
add_action( 'woocommerce_after_variations_form', 'display_variation_group_of_quantity', 11 );
function display_variation_group_of_quantity() {
?>
<script type="text/javascript">
jQuery( function($){
var text = '<?php _e('Grouped by quantity of ', 'woocommerce'); ?>',
sel = 'grouped_quantity',
html = '<span class="'+sel+'"></span>',
form = $('form.variations_form');
// In META Product Section, add after the sku, specific html line for the custom field value
$('div.product_meta .sku_wrapper').after(html)
// On select variation display your custom field html
form.on('show_variation', function( event, data ){
$('span.'+sel).html(text+'<strong>'+data.grouped_quantity+'</strong>');
console.log(data.grouped_quantity); // For testing - To be removed
});
// On unselect variation set an empty value
form.on('hide_variation', function(){
$('span.'+sel).html('');
});
});
</script>
<?php
}
代码放在活动子主题(或活动主题)的函数.php文件中.经过测试,效果良好.
您将得到如下内容: