Temani Afif
Temani Afif

Reputation: 272723

What is the last hook triggered before an order is created in WooCommerce?

I am trying to validate the content of a cart before allowing the order to be placed. This seems to be a trivial task using common hooks like woocommerce_checkout_process action hook, which works fine in most of the cases.

In the website I am working on, it seems there is some complex cases where other plugins are editing the content of the cart thus the above hook isn't enough.

I want to know what is the last hook called before the order is created in the database and before any payment is done. I want to make sure I run my validation after any potential changes to avoid non-needed orders.

I have looked around here: https://woocommerce.github.io/code-reference/hooks/hooks.html searching with the keyword order but there is a ton of results.

I have identified (I guess) the create() function which contain the hook woocommerce_new_order_item but this one is called after the creation not before.

Which hook will make sure there is no changes done between my validation and the creation of orders?

Upvotes: 2

Views: 5456

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253804

Last hook before order creation is woocommerce_checkout_create_order located in WC_Checkout method create_order() As you can see the order is created just after this hook with the code line:

$order->save();

For order items (the following hooks are also located in WC_Checkout method create_order(), before order creation):

  • "line" items use woocommerce_checkout_create_order_line_item filter hook.
  • "fee" items use woocommerce_checkout_create_order_fee_item filter hook.
  • "shipping" items use woocommerce_checkout_create_order_shipping_item filter hook.
  • "tax" items use woocommerce_checkout_create_order_tax_item filter hook.
  • "coupon" items use woocommerce_checkout_create_order_coupon_item filter hook.

Now for fields validation, you can use 2 different hooks located in WC_Checkout class:

Upvotes: 7

Related Questions