Woocommerce wc_price 过滤器使用

Woocommerce wc_price filter usage

我对 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

挂钩 wc_price 是格式化价格挂钩……您应该改用 woocommerce_product_get_price 过滤器挂钩:

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 to WC_Product object type.