首頁  >  問答  >  主體

將 WooCommerce 0 銷售價格替換為自訂文本,並保留常規價格刪除線

我一直在嘗試將 WooCommerce 產品的銷售價格僅更改為「會員免費」而不是 0。 我想將銷售價格更改為自訂文本,例如:

我在網路上搜尋並找到了做同樣事情的程式碼片段,但問題是它也改變了銷售價格和正常價格。

這是我在 Stack Overflow 上找到的程式碼:

function my_wc_custom_get_price_html( $price, $product ) {
    if ( $product->get_price() == 0 ) {
        if ( $product->is_on_sale() && $product->get_regular_price() ) {
            $regular_price = wc_get_price_to_display( $product, array( 'qty' => 1, 'price' => $product->get_regular_price() ) );

            $price = wc_format_price_range( $regular_price, __( 'Free for members!', 'woocommerce' ) );
        } else {
            $price = '<span class="amount">' . __( 'Free!', 'woocommerce' ) . '</span>';
        }
    }

    return $price;
}

add_filter( 'woocommerce_get_price_html', 'my_wc_custom_get_price_html', 10, 2 );

問題是此程式碼也刪除了正常價格上的刪除線。這是我嘗試添加一些內聯 CSS 來添加刪除線時的結果:

我想要實現的是更改銷售價格,如下螢幕截圖所示:

P粉190883225P粉190883225185 天前336

全部回覆(1)我來回復

  • P粉420868294

    P粉4208682942024-03-23 09:05:34

    當產品以 0(零)價格促銷時,請嘗試使用以下簡化代碼以自訂文字顯示帶刪除線的正常價格:

    add_filter( 'woocommerce_get_price_html', 'custom_formatted_sale_price_html', 10, 2 );
    function custom_formatted_sale_price_html( $price_html, $product ) {
        if ( $product->is_on_sale() && $product->get_price() !== 0 ) {
            $regular_price   = wc_get_price_to_display( $product, array( 'price' => $product->get_regular_price() ) );
            $sale_price_text = $regular_price > 0 ? __( 'Free only for members!', 'woocommerce' ) : __( 'Free!', 'woocommerce' );
            $style           = $regular_price > 0 ? ' style="background-color:#08A04B;color:white;padding:0 5px;"' : '';
     
            return '<del aria-hidden="true">' . wc_price( $regular_price ) . '</del> <span'.$style.'>' .  $sale_price_text . '</span>';
        }
        return $price_html;
    }
    

    它應該按您的預期工作。

    回覆
    0
  • 取消回覆