根据产品类别更改结帐货币

时间:2020-10-24 10:04:01

标签: php wordpress woocommerce hook-woocommerce

我需要根据产品类别更改购物车和结帐货币。因此,如果类别为“服装”,则购物车和结帐时的货币应为EUR(并且需要以EUR进行收费)。否则,如果产品未附加“服装”类别,则保留默认的美元货币。

此代码基本上更改了“服装”类别的默认货币,但仅在产品页面上,它在购物车和结帐时没有更改。我也需要在购物车和结帐时进行更改,并且需要收费以这种货币发生。

add_filter('woocommerce_currency', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency ) {
global $post, $product;

if ( has_term( 'clothing', 'product_cat' ) ) {

return 'EUR';
}else{
return $currency;
}
}

我了解购物车和结帐每种产品只能使用一种货币。因此,设置一些限制以使每个购物车只允许一种产品可能会发生以下情况:

add_filter( 'woocommerce_add_to_cart_validation', 'bbloomer_only_one_in_cart', 99, 2 );
   
function bbloomer_only_one_in_cart( $passed, $added_product_id ) {
   wc_empty_cart();
   return $passed;
}

4 个答案:

答案 0 :(得分:1)

我已经做了一些研究,并且在按类别或每种产品动态更改货币时,还有很多其他复杂性。

我假设购物车仍需要计算总数,并提供1种结帐货币。这意味着总计也必须转换。

您会发现最好的答案是通过this plugin's代码进行的挖掘……但是我警告您,这比更改符号要复杂得多。

答案 1 :(得分:0)

也许,这是一个解决方案(我无法尝试):

add_filter('option_woocommerce_currency', function ($currency) {
    // is current page is product-single
    if(is_single('product')) {
        return has_term('clothing', 'product_cat') ? 'EUR' : $currency;
    }
    // for every else pages
    global $woocommerce;
    foreach($woocommerce->cart->get_cart() as $product) {
        if (has_term('clothing', 'product_cat', $product['product_id'])) {
            return 'EUR';
        }
    }
    return $currency;
}, 10, 1);

PS:它不会在产品列表页面上完成这项工作。

答案 2 :(得分:0)

add_filter('woocommerce_currency', 'change_existing_currency_symbol', 10, 2);
function change_existing_currency_symbol( $currency ) {
global $post, $product;
$defaultCurrency = 'EUR';
$categoriesCurrencies = [ 
          'audio'=>'EUR', 
          'mobile'=>'LEK'
];
 return $categoriesCurrencies[$product->category] ?: $defaultCurrency;
}

答案 3 :(得分:0)

我认为这是您的问题的答案,尽管不是推荐的方法,因为它在产品列表页面上不起作用。请尝试使用此代码,让我知道您的想法。

add_filter('woocommerce_currency', 'change_existing_currency_symbol', 10, 1);
function change_existing_currency_symbol( $currency ) {

    if ( is_product() ) {
        if ( has_term( 'clothing', 'product_cat' ) ) return 'EUR';
    } else if ( is_cart() || is_checkout() ) {
        global $woocommerce;
        foreach ( $woocommerce->cart->get_cart() as $product ) {
            if ( has_term('clothing', 'product_cat', $product['product_id'] ) ) return 'EUR';
        }
    }

    return $currency;
}