为了账号安全,请及时绑定邮箱和手机立即绑定

使用短代码显示选定的 WooCommerce 变体格式化价格

使用短代码显示选定的 WooCommerce 变体格式化价格

PHP
慕森卡 2023-09-08 21:49:10
我创建了这段代码,可以在网站上的任何页面上显示价格,该价格由 woocommerce 控制。add_shortcode( 'hhs_product_price', 'hhs_woo_product_price_shortcode' );function hhs_woo_product_price_shortcode( $atts ) {    $atts = shortcode_atts( array(        'id' => null    ), $atts, 'hhs_product_price' );     if ( empty( $atts[ 'id' ] ) ) {        return '';    }    $product = wc_get_product( $atts['id'] );    if ( ! $product ) {        return '';    }    return $product->get_price_html();} 我想做的是修改代码,以便客户选择具有变体的产品。然后价格发生变化以显示变化价格。例如,现在如果一个人选择一种产品,在本例中是酊剂瓶,价格变化与瓶子的尺寸有关。在产品页面上,他们看到以下内容:-产品(酊剂) $30 - $50他们可以从下拉菜单中选择 10 毫克瓶装(30 美元)、15 毫克瓶装(40 美元)或 20 毫克瓶装(50 美元)。因此,如果一个人选择 20mg 选项,价格应显示 50 美元,而不是 30 - 50 美元我已经在 stackoverflow 上看过各种有类似问题的帖子,但这些解决方案都不适合我显示 woocommerce 可变产品价格Woocommerce 获取变化产品价格任何帮助将不胜感激。
查看完整描述

2 回答

?
繁花不似锦

TA贡献1851条经验 获得超4个赞

要显示可变产品变体中选定的产品价格,需要 jQuery。因此,以下短代码将处理所有产品类型,包括可变产品及其价格变化:


add_shortcode( 'product_price', 'display_formatted_product_price' );

function display_formatted_product_price( $atts ) {

    extract(shortcode_atts( array(

        'id' => null

    ), $atts, 'product_price' ) );


    global $product;


    if( ! empty($id) || ! is_a($product, 'WC_Product') ) {

        $product = wc_get_product( empty($id) ? get_the_id() : $id );

    }


    $price_html = $product->get_price_html();


    // Others product types than variable

    if ( ! $product->is_type('variable') ) {

        return '<span class="product-price">' . $price_html . '</span>';

    }

    // For variable products

    else {

        ob_start();


        ?>

        <script type="text/javascript">

        jQuery( function($){

            var p = '<?php echo $price_html; ?>', s = 'span.product-price';


            $( 'form.variations_form.cart' ).on('show_variation', function(event, data) {

                $(s).html(data.price_html); // Display the selected variation price

            });


            $( 'form.variations_form.cart' ).on('hide_variation', function() {

                $(s).html(p); // Display the variable product price range

            });

        });

        </script>

        <?php


        return ob_get_clean() . '<span class="product-price">' . $price_html . '</span>';

    }

}

代码位于活动子主题(或活动主题)的functions.php 文件中。经过测试并有效。


用途:


[product_price]在 php 代码中使用or echo do_shortcode('[product_price]')。


您还可以定义产品 ID,例如(例如产品 id 37):[product_price id="37"]


查看完整回答
反对 回复 2023-09-08
?
GCT1015

TA贡献1827条经验 获得超4个赞

我对一个问题很头疼:如果产品变体都具有相同的价格,则price_html将返回空(。我使用上面 github 转换中找到的过滤器解决了这个问题:

add_filter( 'woocommerce_show_variation_price', '__return_true');


查看完整回答
反对 回复 2023-09-08
  • 2 回答
  • 0 关注
  • 62 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信