用自定义文本替换 WooCommerce 0 销售价格,并保留常规价格删除线

问题描述 投票:0回答:1

我一直在尝试将 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 来添加删除线时的结果:

我想要实现的是更改销售价格,如下屏幕截图所示:

php wordpress woocommerce product
1个回答
2
投票

当产品以 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;
}

它应该按您的预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.