Change currency symbol based on product category in Woocommerce

╄→尐↘猪︶ㄣ 提交于 2019-12-22 18:42:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!