根据 Woocommerce 中的产品类别更改货币符号

Change currency symbol based on product category in Woocommerce

我正在尝试根据产品类别更改默认的 Woocommerce 货币符号。

我的默认 WC 货币设置为美元,我所有的产品在价格前显示 '$' 前缀。但是我不想显示 '$',而是只想显示 'clearance' 类别中的产品 '$$$'

这是我的代码:

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;
    }       
}

有效,“$$$”仅针对 'clearance' 类别中的产品显示,但它会从其余类别中的所有产品中删除“$”。

我需要 if 语句在不满足条件时不执行任何操作。

我也尝试过使用 endif 结束标记,如下所示:

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;      
}

但这里也是一样。它显示 'clearance' 类别中所有产品的 '$$$',但删除任何其他产品的 '$'

我做错了什么?

Related: Custom cart item currency symbol based on product category in Woocommerce 3.3+

您需要将 return $currency_symbol; 放在 if 语句之外:

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
}

代码进入您的活动子主题(或活动主题)的 function.php 文件。

现在应该可以了。

为当前主题创建一个子主题可能是解决方案,但我认为如果您只想更改符号,则不必做那么多。

只需转到 woocommerce 后端文件..

wp-content/plugins/woocommerce/includes/wc-core-functions.php

如果您的 Wordpress 主题中没有后端文件多余的下载文件管理器,您将在主站点中看到这些文件夹。

wp-content>>plugins>>woocommerce>>includes>>wc-core-functions.php

wc-core-function.php 文件中你会看到符号

enter image description here