对于我的 WooCommerce 可变产品,我在单个产品页面上实现自定义尺寸选择器,并将这些尺寸放在表格中:
这些变化只是:30B
30C
30D
而不是被分成:30
and B
C
D
我想弄清楚的是:如何获取每个产品变体的运输类别?
我的购物车页面上有类似的内容,但我不知道变体 ID 是什么,也不知道如何从单个产品页面获取它:
$product_id = ( 0 != $cart_item['variation_id'] ) ? $cart_item['variation_id'] : $cart_item['product_id'];
// need the variation id for the above to be able to do the rest:
$product_shipping_classes = get_the_terms( $product_id, 'product_shipping_class' );
$product_shipping_class_name = ( $product_shipping_classes && ! is_wp_error( $product_shipping_classes ) ) ? current( $product_shipping_classes )->name : '';
一旦获得变体 ID,我就知道该怎么做。我只是不知道如何获得它来完成剩下的事情。我唯一需要获取的是产品 ID 和变体的 slug(此页面上还有一个颜色属性)。
然而,我已经给了产品一个默认的变体来使用(所以隐藏的variation_id
已设置)。
也许需要首先获取以了解所选颜色的 id,然后获取其他颜色的变体 id?
在可变产品的 WooCommerce 产品单页中,您无法在 PHP 中获取所选产品变体,因为它是实时事件(客户端,而不是服务器端)。
实现方法是使用 JavaScript/jQuery 来获取它。由于您没有为该单个产品页面提供有关您的可变产品的任何相关代码,因此我不可能为您提供完全满足您需求的真实工作代码。
获取单个产品页面上为可变产品选择的变体 ID(在此示例中,我在“添加到购物车”按钮下方动态显示所选变体 ID):
add_action( 'woocommerce_single_product_summary', 'single_product_variable_customization', 3, 0 );
function single_product_variable_customization() {
global $product;
// Only for variable products on single product pages
if ( $product->is_type('variable') && is_product() ) {
## ==> ==> Here goes your php code (if needed) ==> ==> ##
// Passing a variable to javascript
$string1 = "The selected Variation ID is: ";
$string2 = "No Variation ID is selected ";
?>
<script>
jQuery(document).ready(function($) {
// Initializing
var myText1 = '<?php echo $string1; ?>', myText2 = '<?php echo $string2; ?>';
// Get and display the default variation ID after add-to-cart button (initialization)
if( '' != $('input.variation_id').val() )
$('div.woocommerce-variation-add-to-cart').after('<div class="selected-variation-id">'+myText1+$('input.variation_id').val()+'</div>');
else
$('div.woocommerce-variation-add-to-cart').after('<div class="selected-variation-id">'+myText2+'</div>'); // No ID selected
console.log($('input.variation_id').val()); // Output in the browser console
// Get and display the chosen variation ID after add-to-cart button
$('select').blur( function(){
if( '' != $('input.variation_id').val() )
$('div.selected-variation-id').html(myText1+$('input.variation_id').val());
else
$('div.selected-variation-id').html(myText2); // No ID selected
console.log($('input.variation_id').val()); // Output in the browser console
});
});
</script>
<?php
}
}
代码位于活动子主题(或主题)的 function.php 文件中或任何插件文件中。
此代码在 WooCommerce 3+ 下进行了测试并且可以工作。
因此,在此基础上,您可以创建自己的函数来满足您的要求(因为您不再提供必要的细节或代码)。
一些相关的答案示例用法(使用 jQuery 和 Woocommerce 单一产品页面):
- 重命名 WooCommerce 3 中缺货产品的“添加到购物车”按钮
- 将可变产品价格替换为 WooCommerce 3 中选择的变化价格
- 可变产品选择器:获取实时选择的值
- 将所选产品变型数据传递到联系表 7 查询表中
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)