首页  >  问答  >  正文

将 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 天前335

全部回复(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
  • 取消回复