问题
I am trying to change the default Woocommerce currency symbol based on the product category.
My default WC currency is set to USD and all my products display with '$'
prefix before the price. But instead of '$'
, I would like to show '$$$'
only for the products that are in 'clearance'
category.
This is my code:
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency_symbol, $currency ) {
global $post, $product, $woocommerce;
if ( has_term( 'clearance', 'product_cat' ) ) {
switch( $currency ) {
case 'USD': $currency_symbol = '$$$'; break;
}
return $currency_symbol;
}
}
It works, and '$$$' is displayed only for the products within the 'clearance' category, however it removes the '$' from all products in the remaining categories.
I need that if statement to do nothing if the condition is not met.
I've also tried with endif
closing tag like this:
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency_symbol, $currency ) {
global $post, $product, $woocommerce;
if ( has_term( 'clearance', 'product_cat' ) ) :
switch( $currency ) {
case 'USD': $currency_symbol = '$$$'; break;
}
return $currency_symbol;
endif;
}
but same thing here. It shows '$$$'
for all products within 'clearance' category, but removes the '$'
for any other product.
What am I doing wrong?
回答1:
Related: Custom cart item currency symbol based on product category in Woocommerce 3.3+
You need to put return $currency_symbol;
outside the if
statement this way:
add_filter('woocommerce_currency_symbol', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency_symbol, $currency ) {
global $post, $product;
if ( has_term( 'clearance', 'product_cat' ) ) {
switch( $currency ) {
case 'USD': $currency_symbol = '$$$';
break;
}
}
return $currency_symbol; // <== HERE
}
Code goes in function.php file of your active child theme (or active theme).
Now it should work.
来源:https://stackoverflow.com/questions/48420586/change-currency-symbol-based-on-product-category-in-woocommerce