WooCommerce可变产品:显示带有不同价格的自定义文本的最低价格 [英] WooCommerce variable products: Display the min price with a custom text for different prices
问题描述
我正在为Woocommerce设置一个功能,该功能显示折扣价格和可变产品的常规价格,该功能在价格范围之前添加一个"from to"文本.
I'm setting up a function for Woocommerce that display discount price and the regular price for variable product, this function add a " from to " text before the price range.
"" 答案线程与我正在寻找的商品最匹配,并且像魅力一样工作!
The "WooCommerce variable products: keep only "min" price with a custom label" answer thread matches the best with what I am looking for and work like a charm!
但是,当可变产品的所有变体都具有相同的价格时,不应显示起始于".
But when all variations in a variable product have the same prices, the " start from " should not be displayed.
所以我做了一个简单的尝试,并在"if"条件下添加
So I've made a simple try and add below the "if" condition
else {
$price = sprintf( __( '%1$s', 'woocommerce' ), $min_price_html );
return $price;
}
并整合到if条件中:
$price = sprintf( __( 'À partir de %1$s', 'woocommerce' ), $min_price_html );
return $price;
但这并没有真正起作用.感谢并欢迎您提供一些帮助.
But it doesn't really work. Some help is appreciated and welcome.
推荐答案
To handle when all variations of a variable product are the same, you need to use array_unique()
php function and count()
to look if all variation prices are the same.
因此代码将略有不同:
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文件中,也可能会出现在任何插件文件中.
这篇关于WooCommerce可变产品:显示带有不同价格的自定义文本的最低价格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!