我对 wc_price 过滤器的可用性有疑问,当我查看代码时 [ https://docs.woocommerce.com/wc-apidocs/source-function-wc_price.html#489]我可以找到 wc_price 过滤器。
function wc_price( $price, $args = array() ) {
extract( apply_filters( 'wc_price_args', wp_parse_args( $args, array(
'ex_tax_label' => false,
'currency' => '',
'decimal_separator' => wc_get_price_decimal_separator(),
'thousand_separator' => wc_get_price_thousand_separator(),
'decimals' => wc_get_price_decimals(),
'price_format' => get_woocommerce_price_format(),
) ) ) );
$negative = $price < 0;
$price = apply_filters( 'raw_woocommerce_price', floatval( $negative ? $price * -1 : $price ) );
$price = apply_filters( 'formatted_woocommerce_price', number_format( $price, $decimals, $decimal_separator, $thousand_separator ), $price, $decimals, $decimal_separator, $thousand_separator );
if ( apply_filters( 'woocommerce_price_trim_zeros', false ) && $decimals > 0 ) {
$price = wc_trim_zeros( $price );
}
$formatted_price = ( $negative ? '-' : '' ) . sprintf( $price_format, '<span class="woocommerce-Price-currencySymbol">' . get_woocommerce_currency_symbol( $currency ) . '</span>', $price );
$return = '<span class="woocommerce-Price-amount amount">' . $formatted_price . '</span>';
if ( $ex_tax_label && wc_tax_enabled() ) {
$return .= ' <small class="woocommerce-Price-taxLabel tax_label">' . WC()->countries->ex_tax_or_vat() . '</small>';
}
return apply_filters( 'wc_price', $return, $price, $args );
}
这意味着该过滤器用于更改产品价格。
所以现在我想通过代码将前端价格加倍。所以我写了下面的函数
add_filter( 'wc_price', 'double_price', 10, 3 );
function double_price( $return, $price, $args){
$price=$price*2;
return $price;
}
现在价格显示在前端,没有货币符号。
然后我这样重写
function double_price( $return, $price, $args){
$price=$price*2;
return '<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>'.$price.'</span>';
}
现在可以使用了。
但我认为这不是正确的方法。 有人可以解释一下我如何正确使用此功能。。此过滤器中的 $args,$price,$retun
有什么用?
此外,如果我需要根据类别更改所有产品价格,我如何获取此过滤器中的产品 ID?如果我写产品 ID 那么我会写
function double_price( $return, $price, $args){
$price=$price*2;
if( has_term( 'shirts', 'product_cat' ,$product->ID) ) {
$price=130;
}
return '<span class="woocommerce-Price-amount amount"><span class="woocommerce-Price-currencySymbol">£</span>'.$price.'</span>';
}
Please note: this question have a sub question After using woocommerce_product_get_price hook the checkout page price is incorrect
最佳答案
Hook wc_price
是一个格式化价格 Hook ...您应该使用woocommerce_product_get_price
过滤器 Hook :
add_filter( 'woocommerce_product_get_price', 'double_price', 10, 2 );
function double_price( $price, $product ){
return $price*2;
}
已测试并正常工作
代码位于事件子主题(或主题)的 function.php 文件中或任何插件文件中。
This hook is fired before any formatting price function and it's a composite hook based on
get_price()
method here applied toWC_Product
object type.
关于php - Woocommerce wc_price 过滤器使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47786331/