php - 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;
但它并没有真正起作用。一些帮助表示赞赏和欢迎。
解决方案
要处理可变产品的所有变体都相同的情况,您需要使用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 文件中,也位于任何插件文件中。
推荐阅读
- powershell - Autodesk Revit 的启动过程等待问题
- jenkins - 多管道詹金斯
- javascript - ChartJS 中的条形颜色未更新
- spring-boot - 升级到Spring-boot 2.3.1.RELEASE和kafka,找不到kafka.utils.TestUtils
- java - 在 JOptionPane 内的 JScrollPane 上方添加文本
- javascript - 无法从“App.js”解析“@react-navigation/stack”
- c# - LINQ to Entities 无法识别 System.String
- css - 第一次连接提供了不受支持的 MIME 类型,但在浏览器刷新后工作正常吗?
- ffmpeg - 如何将带有ffmpeg的流保存到块中,但是在临时名称中并将名称更改为const
- android - UnsatisfiedLinkError: dlopen failed: library "libm.so.6" not found - Android Studio 4.0