问题描述
在可变产品页面上的“添加到购物车”按钮后,我试图在单个产品页面上显示选定的产品变体描述。
下面是我已实现的代码,但似乎没有用:
add_action( 'woocommerce_after_add_to_cart_form','description_below_add_cart',11 );
function description_below_add_cart() {
global $post;
$terms = wp_get_post_terms( $post->ID,'product_cat' );
foreach ( $terms as $term ) $categories[] = $term->slug;
if ( in_array( 'cookware',$categories ) ) {
global $product;
$weight = $product->get_weight();
$dimensions = wc_format_dimensions($product->get_dimensions(false));
echo '<div class="short-description">' . $item['product']->get_description() .'</div>';
}
}
在添加到可变产品的购物车按钮后,如何显示Woocommerce中所选产品变体的特定数据(变体描述)?
解决方法
已更新:关于产品类别部分,您当前的代码可以简化一些。我添加了一些代码,以显示来自可变产品页面的所选产品变体的变体描述。
这里是显示所选产品变体描述的方法(需要一些JQuery):
add_action( 'woocommerce_after_add_to_cart_form','description_below_add_cart',11 );
function description_below_add_cart() {
global $product;
$terms_slugs = wp_get_post_terms( $product->get_id(),'product_cat',array('fields' => 'slugs') ); // Get the terms slugs
// Only for 'cookware' product category
if ( in_array( 'cookware',$terms_slugs ) ) {
$weight = $product->get_weight();
$weight = ! empty($weight) ? wc_format_weight($weight) : '';
$dimensions = $product->get_dimensions(false);
$dimensions = ! empty($dimensions) ? wc_format_dimensions($dimensions) : '';
// For variable products
if ( $product->is_type('variable') ) {
// Display the selected variation description
echo '<div class="selected-variation-description"></div>';
?>
<script type="text/javascript">
jQuery( function($){
// On select variation display variation description
$('form.variations_form').on('show_variation',function( event,data ){
$('div.selected-variation-description').html(data.variation_description);
console.log(data.variation_description);
});
// On unselect variation remove variation description
$('form.variations_form').on('hide_variation',function(){
$('div.selected-variation-description').html('');
});
});
</script>
<?php
}
}
}
代码进入活动子主题(或活动主题)的functions.php文件中。经过测试,可以正常工作。