首页 > 解决方案 > Woocommerce中不带小数的自定义可变产品格式价格

问题描述

我目前在激活的子主题的functions.php中使用此附加代码来删除产品使用变体时的价格范围(因此它只会显示价格“来自:X$”而不是“来自:X$ - Y$"):

add_filter( 'woocommerce_variable_sale_price_html',
'lw_variable_product_price', 10, 2 );
add_filter( 'woocommerce_variable_price_html',
'lw_variable_product_price', 10, 2 );

function lw_variable_product_price( $v_price, $v_product ) {

// Regular Price
$v_prices = array( $v_product->get_variation_price( 'min', true ),
                            $v_product->get_variation_price( 'max', true ) );
$v_price = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s', 'woocommerce'),
                       wc_price( $v_prices[0] ) ) : wc_price( $v_prices[0] );

// Sale Price
$v_prices = array( $v_product->get_variation_regular_price( 'min', true ),
                          $v_product->get_variation_regular_price( 'max', true ) );
sort( $v_prices );
$v_saleprice = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s','woocommerce')
                      , wc_price( $v_prices[0] ) ) : wc_price( $v_prices[0] );

if ( $v_price !== $v_saleprice ) {
$v_price = '<del>'.$v_saleprice.$v_product->get_price_suffix() . '</del> <ins>' .
                       $v_price . $v_product->get_price_suffix() . '</ins>';
}
return $v_price;
}

这里唯一的问题已经在标题中提到了。我需要在产品列表(默认商店页面)中显示不带小数的价格,不像它目前显示的那样: 在此处输入图像描述

我确信如果没有这个额外的代码,我正在使用它没有这些零。

相信我,如果没有最后的两个零,它看起来好多了。

标签: phpwordpresswoocommerceproductprice

解决方案


要显示不带小数的价格,您需要'decimals'在 Woocommerce格式化函数中使用参数wc_price()...</p>

因此,例如价格为499.00,您将添加到wc_price()参数中array('decimals' => 0)

echo wc_price( 499.00, array('decimals' => 0) );

它将输出不带小数的格式化 html 价格。

如您所见,它使用 wc_price() 函数从任何格式化价格中删除小数点,例如在您的代码中:

$v_price = $v_prices[0]!==$v_prices[1] ? sprintf(__('From: %1$s', 'woocommerce'),
wc_price( $v_prices[0], array('decimals' => 0) ) ) : wc_price( $v_prices[0], array('decimals' => 0) );

对于可变产品定制价格,正如您所想,请参阅以下答案:

WooCommerce 可变产品:仅保留带有自定义标签的“最低”价格

您只需添加array('decimals' => 0)wc_price()功能


推荐阅读