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

标签 php wordpress if-statement woocommerce currency

我正在尝试根据产品类别更改默认的 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;
    }       
}

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

如果条件不满足,我需要 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;      
}

但这里也是同样的事情。它为“清仓”类别中的所有产品显示 '$$$',但删除任何其他产品的 '$'

我做错了什么?

最佳答案

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 文件中。

现在应该可以工作了。

关于php - 根据 Woocommerce 中的产品类别更改货币符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48420586/

相关文章:

javascript - 如何在 jQuery 中包含多个 if 语句条件

php - Laravel 4 Controller 中的依赖注入(inject)实例所有对象

php - 在 PHP 中与 memcached 的持久连接

php - Issu 必须获取新的交易 ID 一直显示第一个交易 ID

javascript - Superfish IE7 z-index 错误与 Nivo slider 或 wordpress 中的 Photospace

wordpress - 是否可以在可分页容器(视觉 Composer )上使用箭头?

java - 编码帮助(If 语句)

php - 如何使用 PHP 从 UTF-8 数据库输出反斜杠?

wordpress - 停止 WordPress 修订并自动保存到页面

Python - Tkinter RadioButton If 语句