php - 显示 Woocommerce 中选定产品变体的特定数据

标签 php jquery wordpress woocommerce product-variations

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

下面是我实现的代码,但它似乎不起作用:

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>';
    }
}

Here是网站的产品页面。

在可变产品的“添加到购物车”按钮后,如何显示 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 文件中。经过测试并有效。

关于php - 显示 Woocommerce 中选定产品变体的特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64761045/

相关文章:

php - Mysql PHP查询更新

php - 如何对小数进行四舍五入?

javascript - adapt.js 960 gs 与 wordpress

php - 如何使用 ajax 更新我的 session ?

css - WordPress 短代码无法正常工作

php - Artisan 迁移在新项目的服务器中显示错误

javascript - 使用 jQuery 保留文本框值

javascript - 如何将 JSON 数据转换为 HTML

javascript - 执行具有滑动延迟的功能

php - 如何在mysql中为图像设置标签/关键字