Get full tax from the basket Total programmatically in WooCommerce

How to get the total tax amount in WooCommerce on a page in WordPress using: functions.php

global $woocommerce;

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

But does not return any value.

How can I get the total tax from the basket?

In fact, I want the tax to be calculated for the user, but then it will decrease, as the client will pay taxes on the COD.

Full code below:

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' );
+4
source share
2 answers
  • global $woocommerce; $woocommerce->cartdeprecated for cart. Use instead . Here you can directly use the (object) argument ... WC()->cart
    $cart
  • The correct property instead . taxes tax_total
  • 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 );
}

function.php ( ), .

.

+3

. : -

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( );
+1

Source: https://habr.com/ru/post/1674869/


All Articles