Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

php - Get the order ID in checkout page before payment process

In WooCommerce, I need to get order ID right in checkout page of WooCoommerce, before payment, when the order is created.

I look at all sessions and tried to find out when order goes for payment in order_awaiting_payment session, but I need it before going for payment.
So I think about a solution that is make order when checkout page loaded (In fact make it ready for payment) and when checkout real complete update it.

How to get order ID in checkout page before order go for payment in WooCommerce?

I think there is some hook for this but I can't find it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use a custom function hooked in woocommerce_checkout_order_processed action hook.
Since woocommerce 3.0+ version, here Is the corresponding core code located in process_checkout() function.

// Since WooCommerce version 3.0+
do_action( 'woocommerce_checkout_order_processed', $order_id, $posted_data, $order );

and below WooCommerce 3.0 version:

// Since WooCommerce version 2.1+ (before version 3.0+)
do_action( 'woocommerce_checkout_order_processed', $order_id, $this->posted );

So there is 2 cases depending which version of woocommerce you are using:

Since WooCommerce 3.0+ you can use 2 additional arguments in your hooked function and you will not need to create an instance of the order object as you get $order already as an argument.
You will be able also to access the posted data directly through $posted_data argument.

add_action('woocommerce_checkout_order_processed', 'action_checkout_order_processed', 10, 3);
function action_checkout_order_processed( $order_id, $posted_data, $order ) {
   // Do something
}

Since WooCommerce 2.1+ (Before WooCommerce 3.0), you have only the $order_id as argument, so you might be need to get an instance of $order object with wc_get_order() function:

add_action('woocommerce_checkout_order_processed', 'action_checkout_order_processed', 10, 1);
function action_checkout_order_processed( $order_id ) {
   // get an instance of the order object
   $order = wc_get_order( $order_id );

   // Do something
}

The Code goes in function.php file of your active child theme (or theme) or also in any plugin file.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...