首页 > 解决方案 > WooCommerce 可变产品:使用不同价格的自定义文本显示最低价格

问题描述

我正在为 Woocommerce 设置一个函数,显示折扣价格和可变产品的正常价格,这个函数在价格范围之前添加一个“从到”文本。

WooCommerce 可变产品:仅保留带有自定义标签的“最低”价格”答案线程与我正在寻找的东西最匹配,并且像魅力一样工作!

但是,当变量产品中的所有变量都具有相同的价格时,不应显示“开始于”。

所以我做了一个简单的尝试并在“if”条件下添加

else {
    $price = sprintf( __( '%1$s', 'woocommerce' ), $min_price_html );
return $price;
}

并融入 if 条件:

$price = sprintf( __( 'À partir de %1$s', 'woocommerce' ), $min_price_html );
    return $price; 

但它并没有真正起作用。一些帮助表示赞赏和欢迎。

标签: phpwordpresswoocommercehook-woocommerceprice

解决方案


要处理可变产品的所有变体都相同的情况,您需要使用array_unique()php 函数并count()查看所有变体价格是否相同。

所以代码会略有不同:

add_filter( 'woocommerce_variable_price_html', 'custom_min_max_variable_price_html', 10, 2 );
function custom_min_max_variable_price_html( $price, $product ) {
    $prices = $product->get_variation_prices( true );
    $count  = (int) count( array_unique( $prices['price'] ));

    // When all variations prices are the same
    if( $count === 1 )
        return $price;

    $min_price = current( $prices['price'] );
    $min_keys  = current(array_keys( $prices['price'] ));

    $min_reg_price  = $prices['regular_price'][$min_keys];
    $min_price_html = wc_price( $min_price ) . $product->get_price_suffix();

    // When min price is on sale (Can be removed)
    if( $min_reg_price != $min_price ) {
        $min_price_reg_html = '<del>' . wc_price( $min_reg_price ) . $product->get_price_suffix() . '</del>';
        $min_price_html = $min_price_reg_html .'<ins>' . $min_price_html . '</ins>';
    }
    $price = sprintf( __( 'À partir de %s', 'woocommerce' ), $min_price_html );

    return $price;
}

代码位于活动子主题(或主题)的 functions.php 文件中,也位于任何插件文件中。


推荐阅读