在WooCommerce中以编程方式获取购物车税总额

DEV*_*OCB 4 php wordpress cart woocommerce tax

functions.php在WordPress 的页面中,如何使用以下方法在WooCommerce中获取税金总额:

global $woocommerce;

$discount = $woocommerce->cart->tax_total;
Run Code Online (Sandbox Code Playgroud)

但是没有返回任何值。

如何获得购物车税总额?

从本质上讲,我希望为用户计算税金,但是由于客户将支付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' );
Run Code Online (Sandbox Code Playgroud)

Loi*_*tec 5

  1. global $woocommerce; $woocommerce->cart购物车已过时。使用WC()->cart代替。
    在这里,您可以直接使用$cart (对象)参数。
  2. 正确的属性是taxes不是tax_total
  3. 最好使用WC_Cart get_taxes()方法intead与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 );
}
Run Code Online (Sandbox Code Playgroud)

代码在您的活动子主题(或主题)的function.php文件中,或者在任何插件文件中。

此代码已经过测试并且可以工作。