2017-04-15 44 views
4

你如何在WooCommerce税收总额中的WordPress functions.php页,使用:找车总税额编程方式WooCommerce

global $woocommerce; 

$discount = $woocommerce->cart->tax_total; 

但没有返回任何值。

如何获得购物车税总额?

本质上我想税收为用户计算,但随后它会减少,因为客户将支付COD的税收。

全部下面的代码:

add_action('woocommerce_calculate_totals', 'action_cart_calculate_totals', 10, 1); 
function action_cart_calculate_totals($cart_object) { 

    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    if (!WC()->cart->is_empty()): 
     $cart_object->cart_contents_total *= .10 ; 

    endif; 
} 


//Code for removing tax from total collected 
function prefix_add_discount_line($cart) { 

    global $woocommerce; 

    $discount = $woocommerce->cart->tax_total; 

    $woocommerce->cart->add_fee(__('Tax Paid On COD', 'your-text-domain') , - $discount); 

} 
add_action('woocommerce_cart_calculate_fees', 'prefix_add_discount_line'); 

回答

3
  1. global $woocommerce; $woocommerce->cart购物车已过时。改为使用WC()->cart
    在这里,您可以使用,而不是直接$cart(对象)参数...
  2. 正确的属性是taxes,而不是tax_total
  3. 是更好地使用WC_Cart get_taxes()方法这一翻译成与WooCommerce 3.0以上版本

要达到什么样的你想你的代码兼容将是:

// For Woocommerce 2.5+ (2.6.x and 3.0) 
add_action('woocommerce_cart_calculate_fees', 'prefix_add_discount_line', 10, 1); 
function prefix_add_discount_line($cart) { 

    if (is_admin() && ! defined('DOING_AJAX')) 
     return; 

    $discount = 0; 
    // Get the unformated taxes array 
    $taxes = $cart->get_taxes(); 
    // Add each taxes to $discount 
    foreach($taxes as $tax) $discount += $tax; 

    // Applying a discount if not null or equal to zero 
    if ($discount > 0 && ! empty($discount)) 
     $cart->add_fee(__('Tax Paid On COD', 'your-text-domain') , - $discount); 
} 

代码放在功能。你的活动儿童主题(或主题)的php文件或任何插件文件。

此代码已经过测试并可正常工作。

+0

再次你真棒,谢谢 – DEVPROCB

1

您正在使用错误的函数名。正确的功能如下: -

WC()->cart->get_tax_totals(); 

而不是使用$ woocommerce-> cart-> tax_total;要获得购物车总税额,您可以通过从购物车总额中减去不含税的购物车总额来完成此操作。如果你想获得的所有税收数组,那么你可以在下面的代码打通

$total_tax = floatval(preg_replace('#[^\d.]#', '', WC()->cart->get_cart_total())) - WC()->cart->get_total_ex_tax(); 

: - - :

您可以通过下面的代码做到这一点

WC()->cart->get_taxes(); 
相关问题