【问题标题】:Woocommerce variation product price inside Add to cart button添加到购物车按钮内的 Woocommerce 变化产品价格
【发布时间】:2020-04-24 13:44:52
【问题描述】:

我使用 "Display price on add to cart button from the functions.php file in Woocommerce" 答案代码,在简单产品中添加价格。

但我想改进此功能并在按钮内动态显示选择的变化价格。使用变体产品页面上的此代码,它仅显示最低价格。 有什么解决办法吗?

添加到购物车按钮现在的外观(未选择任何选项)

我希望如何展示:

【问题讨论】:

标签: php wordpress woocommerce


【解决方案1】:

也许它会对某人有用! Result. Add to cart button of variable product

add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages
add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages
function custom_add_to_cart_price( $button_text, $product ) {
    // Variable products
    if( $product->is_type('variable') ) {
        // shop and archives
        if( ! is_product() ){

            $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
            return $button_text . ' - From ' . strip_tags( $product_price );
        } 
        // Single product pages
        else {
            $variations_data =[]; // Initializing

        // Loop through variations data
        foreach($product->get_available_variations() as $variation ) {
            // Set for each variation ID the corresponding price in the data array (to be used in jQuery)
            $variations_data[$variation['variation_id']] = $variation['display_price'];
        }
        ?>
        <script>
        jQuery(function($) {
            var jsonData = <?php echo json_encode($variations_data); ?>,
                inputVID = 'input.variation_id';

            $('input').change( function(){
                if( '' != $(inputVID).val() ) {
                    var vid      = $(inputVID).val(), // VARIATION ID
                       vprice   = ''; // Initilizing

                    // Loop through variation IDs / Prices pairs
                    $.each( jsonData, function( index, price ) {
                        if( index == $(inputVID).val() ) {
                            vprice = Math.round(price); // The right variation price
                        }
                    });
                    // Change price dynamically when changing options
                    $( "button.single_add_to_cart_button.button.alt span" ).remove();
                    $(".single_add_to_cart_button").append("<span>" + " " + vprice + " ₴" + "</span>");
                }
            });
        });
        </script><?php
            return $button_text;
        }
    } 
    // All other product types
    else {
        $product_price = wc_price( wc_get_price_to_display( $product ) );
        return $button_text . '  ' . strip_tags( $product_price );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多