2

在可变产品页面上的添加到购物车按钮后,我试图在我的单个产品页面上显示选定的产品变体描述。

下面是我实现的代码,但它似乎没有工作:

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 中显示所选产品变体的特定数据(变体描述) ?

4

1 回答 1

2

更新:关于产品类别部分,您当前的代码可以稍微简化一下。我添加了一些代码来显示可变产品页面中所选产品变体的变体描述。

这是显示所选产品变体描述的方式(需要一些 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 文件中。测试和工作。

于 2020-11-10T02:33:52.123 回答