亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用短代碼顯示選定的 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 關注
  • 130 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號