Woo Dev Patch – Set a Tax Class when Adding a Product to a WooCommerce Order

When creating WooCommerce orders programmatically, adding a product is usually straightforward. But there’s a small detail that can be easy to miss: WooCommerce doesn’t automatically calculate the order’s taxes just because a product has been added.

You may end up with an order containing the correct product and quantity, but with no tax amount reflected in the order totals. The good news is that the fix is simple – you just need to make sure WooCommerce calculates the taxes and totals after adding the product.

In this post, we’ll look at how to add a product to a WooCommerce order programmatically and ensure the correct tax is applied before the order is saved.

Here’s a complete example that adds a product, sets its tax class, calculates the taxes and totals, and saves the order.

// Create new WC Order.
$order = wc_create_order();
$order->set_created_via( 'admin' );

$product = wc_get_product( 123 ); // Sample product with ID: 123
if ( $product ) {
    // Add a new product to the order with qty 2.
    $item_id = $order->add_product( $product, 2 );
    if ( $item_id && $item_id > 0 ) {
        $item = $order->get_item( $item_id );
        $item->set_tax_class( $product->get_tax_class() );
    }
    $order->calculate_taxes();
    $order->calculate_totals();
    $order->save();
}

Why this works

$order->add_product() adds the product and its quantity to the order, but the order’s tax totals are calculated separately.

After adding the product, this snippet explicitly sets the item’s tax class and then asks WooCommerce to calculate the taxes and totals:

$item->set_tax_class( $product->get_tax_class() );
$order->calculate_taxes();
$order->calculate_totals();

calculate_taxes() determines the applicable tax rates and stores the tax data on the order item. calculate_totals() then uses those values when calculating the order subtotal, tax, and grand total.

Common Mistake

A common mistake is to add the product and save the order without recalculating its taxes and totals.

Make sure you call:

$order->calculate_taxes();
$order->calculate_totals();

before saving the order.

Also, if you are explicitly setting the item’s tax class, do so before calling calculate_taxes() so WooCommerce uses the correct tax class when calculating the rates.

HPOS Compatibility

This code is compatible with both HPOS and the legacy WooCommerce order storage system. The WooCommerce CRUD APIs used here handle the underlying storage, so the code does not need to change depending on which order storage system the store uses.

Tested with:

  • WordPress 7.1
  • WooCommerce 11.1.0

1 thought on “Woo Dev Patch – Set a Tax Class when Adding a Product to a WooCommerce Order”

  1. Pingback: Woo Dev Patch – Add a Product to a WooCommerce Order – TechnoVama

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top