Getting order data after successful checkout hook - php

In WooCommerce, I would like to send a request to an API once the customer has successfully checked out. Its basically a website where the client is selling online courses (Like udemy).
When the customer checks out, I would like to send an API request and enroll the user for that particular course. I have tried several WooCommerce hooks but none worked for me.
This is the code that I'm using:
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
function enroll_student($order_id)
{
echo $order_id;
echo "Hooked";
}
I am writing this code for a plugin and to make it easier, I am currently using Cash on Delivery method.
Can anyone point me out where I am going wrong because when I checkout I cant see the message "hooked" that I am printing nor the $order_id?
It takes me to the success page and doesn't show these two things that I am printing.

Update 2 Only For Woocommerce 3+ (added restriction to execute the code only once)
add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
if ( ! $order_id )
return;
// Allow code execution only once
if( ! get_post_meta( $order_id, '_thankyou_action_done', true ) ) {
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
// Get the order key
$order_key = $order->get_order_key();
// Get the order number
$order_key = $order->get_order_number();
if($order->is_paid())
$paid = __('yes');
else
$paid = __('no');
// Loop through order items
foreach ( $order->get_items() as $item_id => $item ) {
// Get the product object
$product = $item->get_product();
// Get the product Id
$product_id = $product->get_id();
// Get the product name
$product_id = $item->get_name();
}
// Output some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
// Flag the action as done (to avoid repetitions on reload for example)
$order->update_meta_data( '_thankyou_action_done', true );
$order->save();
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Related thread:
Get Order items and WC_Order_Item_Product in WooCommerce 3
How to get WooCommerce order details
The code is tested and works.
Updated (to get the product Id from Orders items as asked in your comment)
May be you could use woocommerce_thankyou hook instead, that will display on order-received page your echoed code, this way:
add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
if ( ! $order_id )
return;
// Getting an instance of the order object
$order = wc_get_order( $order_id );
if($order->is_paid())
$paid = 'yes';
else
$paid = 'no';
// iterating through each order items (getting product ID and the product object)
// (work for simple and variable products)
foreach ( $order->get_items() as $item_id => $item ) {
if( $item['variation_id'] > 0 ){
$product_id = $item['variation_id']; // variable product
} else {
$product_id = $item['product_id']; // simple product
}
// Get the product object
$product = wc_get_product( $product_id );
}
// Ouptput some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and works.
Then you can use all class WC_Abstract_Order methods on the $order object.
Related:
How to get WooCommerce order details
Get Order items and WC_Order_Item_Product in WooCommerce 3
How to get Customer details from Order in WooCommerce?

Rather than 'woocommerce_thankyou' hook, 'woocommerce_checkout_order_processed' hook is the relevant hook. 'woocommerce_checkout_order_processed' hook will be called only once and you will not need to add meta for each product and make additional calls to keep check for code to run only once. As, 'woocommerce_thankyou' can be called multiple times that is each time thankyou page loads.
Replace add_action('woocommerce_thankyou', 'enroll_student', 10, 1);
with
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
and remove meta code and checks. Updated code is
add_action('woocommerce_checkout_order_processed', 'enroll_student', 10, 1);
function enroll_student( $order_id ) {
// Getting an instance of the order object
$order = wc_get_order( $order_id );
if($order->is_paid())
$paid = 'yes';
else
$paid = 'no';
// iterating through each order items (getting product ID and the product object)
// (work for simple and variable products)
foreach ( $order->get_items() as $item_id => $item ) {
if( $item['variation_id'] > 0 ){
$product_id = $item['variation_id']; // variable product
} else {
$product_id = $item['product_id']; // simple product
}
// Get the product object
$product = wc_get_product( $product_id );
}
// Ouptput some data
echo '<p>Order ID: '. $order_id . ' — Order Status: ' . $order->get_status() . ' — Order is paid: ' . $paid . '</p>';
}

you can get the order items of an order by
// Getting an instance of the order object
$order = new WC_Order( $order_id );
$items = $order->get_items();
//Loop through them, you can get all the relevant data:
foreach ( $items as $item ) {
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
}

Related

Get used coupon codes and related discount amounts from WooCommerce orders

I need to insert in a custom plugin the code to get the name of the discount codes I enter in the settings, the discount obtained with the code and the total.
Based on Get coupon data from WooCommerce orders answer code, I have inserted the following code:
$order = wc_get_order( $order_id );
// GET THE ORDER COUPON ITEMS
$order_items = $order->get_items('coupon');
// print_r($order_items); // For testing
// LOOP THROUGH ORDER COUPON ITEMS
foreach( $order_items as $item_id => $item ){
// Retrieving the coupon ID reference
$coupon_post_obj = get_page_by_title( $item->get_name(), OBJECT, 'shop_coupon' );
$coupon_id = $coupon_post_obj->ID;
// Get an instance of WC_Coupon object (necessary to use WC_Coupon methods)
$coupon = new WC_Coupon($coupon_id);
## Filtering with your coupon custom types
if( $coupon->is_type( 'fixed' ) || $coupon->is_type( 'percent' ) || $coupon->is_type( 'fixed_product' ) ){
// Get the Coupon discount amounts in the order
$order_discount_amount = wc_get_order_item_meta( $item_id, 'discount_amount', true );
$order_discount_tax_amount = wc_get_order_item_meta( $item_id, 'discount_amount_tax', true );
## Or get the coupon amount object
$coupons_amount = $coupons->get_amount();
}
}
$confirmation = str_ireplace("{order_items}", $order_items, $confirmation);
But the only information it brings back to me, when I do an echo is the word "array".
What am I doing wrong? Any help?
Try the following instead, that will add a coma separated string of applied coupon codes with their respective discount amount:
$order = wc_get_order( $order_id ); // If needed
$output = array(); // Initializing
// loop through order items "coupon"
foreach( $order->get_items('coupon') as $item_id => $item ){
// Get the coupon array data in an unprotected array
$data = $item->get_data();
// Format desired coupon data for output
$output[] = $data['code'] . ': ' . strip_tags( wc_price( $data['discount'] + $data['discount_tax'] ) );
}
$confirmation = str_ireplace("{order_items}", implode(', ', $output), $confirmation);

Display product thumbnails on WooCommerce My account orders list

I am trying to display product thumbnails on WooCommerce My account > Orders list, beside the order number.
Below is the screenshot of the order
What hook I have to use to display the image?
I tried Add the product image to Woocommerce my account order view answer code, but it displays the image on single view orders.
Updated
You can use the following to add product thumbnails on WooCommerce My account > Orders list, beside the order number:
add_action( 'woocommerce_my_account_my_orders_column_order-number', 'my_account_orders_product_thumbnails', 20, 1 );
function my_account_orders_product_thumbnails( $order ) {
echo '' . '#' . $order->get_order_number() . '';
// Loop through order items
foreach( $order->get_items() as $item ) {
$product = $item->get_product(); // Get the WC_Product object (from order item)
$thumbnail = $product->get_image(array( 36, 36)); // Get the product thumbnail (from product object)
if( $product->get_image_id() > 0 ) {
echo ' ' . $thumbnail;
}
}
}
Or you can add a new column with the product thumbnails after the order number like:
add_filter( 'woocommerce_my_account_my_orders_columns', 'filter_woocommerce_my_account_my_orders_columns', 10, 1 );
function filter_woocommerce_my_account_my_orders_columns( $columns ) {
$new_column = array( 'order-number' => $columns['order-number']);
unset($columns['order-number']);
$new_column['order-thumbnails'] = '';
return array_merge($new_column, $columns);
}
add_action( 'woocommerce_my_account_my_orders_column_order-thumbnails', 'filter_woocommerce_my_account_my_orders_column_order', 10, 1 );
function filter_woocommerce_my_account_my_orders_column_order( $order ) {
// Loop through order items
foreach( $order->get_items() as $item ) {
$product = $item->get_product(); // Get the WC_Product object (from order item)
$thumbnail = $product->get_image(array( 36, 36)); // Get the product thumbnail (from product object)
if( $product->get_image_id() > 0 ) {
echo $thumbnail . ' ' ;
}
}
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
This is working fine for me. Unfortunately, the function is not working on Woocommerce Pre-Order plugin and in mobile the graphics are so small.
add_action( 'woocommerce_my_account_my_orders_column_order-number', 'my_account_orders_product_thumbnails', 20, 1 );
function my_account_orders_product_thumbnails( $order ) {
echo '' . '#' . $order->get_order_number() . '';
// Loop through order items
foreach( $order->get_items() as $item ) {
$product = $item->get_product(); // Get the WC_Product object (from order item)
$thumbnail = $product->get_image(array( 36, 36)); // Get the product thumbnail (from product object)
if( $product->get_image_id() > 0 ) {
echo ' ' . $thumbnail;
}
}
}

How to add variables to custom thank you url in Woocommerce

I was able to follow the redirect tutorial https://businessbloomer.com/resolved-woocommerce-redirect-custom-thank-page/
But can't seem to add the woocommerce variables to the url.
I want something like this > http://example.com?EO_ID=M180924-678922&Product_Code=vssx2&Quantity=1&Email=billing_email#gmail.com'
Thanks.
The linked code is outdated and don't handle any URL query string. You should need to make changes and adapt the code.
Note: Orders can have many items, so to make it work for your case we use the first item only.
Try this (you will need to define your URL path for $path variable):
add_action( 'woocommerce_thankyou', 'thankyou_custom_redirect', 5, 1 );
function thankyou_custom_redirect( $order_id ){
// Get the WC_Order object instance
$order = wc_get_order( $order_id );
// Order data
$order_key = $order->get_order_key(); // Get order key (if needed)
$transaction_id= $order->get_transaction_id(); // Get order key (if needed)
$billing_email = $order->get_billing_email(); // Get billing email
$order_num = $order->get_order_number(); // Get order number
$order_date = $order->get_date_created(); // Get order creation date
// Order item data (first item)
$order_items = $order->get_items(); // Get order items
$first_item = reset($order_items); // Keep the first Item
$item_qty = $first_item->get_quantity(); // Item quantity
$product = $first_item->get_product(); // Get the WC_Product object instance
$sku = $product->get_sku(); // Get the product code (SKU)
// Build your query string
$query_string = '?EO_ID=' . $order_date->date('ymd') . -rand(pow(10, 5), pow(10, 6)-1);
$query_string .= '&Product_Code=' . $sku;
$query_string .= '&Quantity=' . $item_qty;
$query_string .= '&Email=' . $billing_email;
$path = '/custom-path/'; // <=== HERE define the url path (without the domain)
$url = home_url( $path . $query_string );
// Not for failed orders
if ( ! $order->has_status( 'failed' ) ) {
wp_redirect( $url );
exit();
}
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

Adding a custom field value to Woocommerce order email template

In Woocommerce with Advanced Custom Fields plugin, we have added a custom field to products and this field value is specific to each product.
Now I am trying to add this custom field value to our Woocommerce order confirmation emails.
I have tried the following code with no success:
<?php
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$order_id = int_val( $order->id ); // Older than 3.0
} else {
$order_id = int_val( $order->get_id() ); // 3.0+
}
$inst1 = get_field(‘how1’, $order_id );
if( $inst1 ){
echo '<p>' . $inst1 . '</p>';
}
?> with Advanced Custom Fields plugin
As your custom field is specific to "product" post type (but NOT to "order" post type) you need to get first the order items to get the product ID that you should use with ACF get_field() function this way:
<?php
foreach ( $order->get_items() as $item ) {
// Get the product ID
if ( version_compare( WC_VERSION, '3.0', '<' ) ) {
$product_id = $item['product_id']; // Older than 3.0
} else {
$product_id = $item->get_product_id(); // 3.0+
}
$inst1 = get_field( 'how1', $product_id );
if( $inst1 ){
echo '<p>' . $inst1 . '</p>';
}
}
<?
The custom field value will be displayed for each item in the order, as an order can have many items in it.
References:
How to get WooCommerce order details
Get Order items and WC_Order_Item_Product in Woocommerce 3

Get the product ID in WooCommerce 3+ Order items

I am trying to get woocommerce thank you page order_id. Using the code below.
But unfortunately I can't get it.
add_action( 'woocommerce_thankyou', 'bbloomer_check_order_product_id');
function bbloomer_check_order_product_id( $order_id ){
$order = new WC_Order( $order_id );
$items = $order->get_items();
foreach ( $items as $item ) {
$product_id = $item['product_id'];
if ( $product_id == XYZ ) {
// do something
}
}
}
This code is outdated for WooCommerce version 3+. You should use instead:
add_action( 'woocommerce_thankyou', 'check_order_product_id', 10, 1);
function check_order_product_id( $order_id ){
# Get an instance of WC_Order object
$order = wc_get_order( $order_id );
# Iterating through each order items (WC_Order_Item_Product objects in WC 3+)
foreach ( $order->get_items() as $item_id => $item_values ) {
// Product_id
$product_id = $item_values->get_product_id();
// OR the Product id from the item data
$item_data = $item_values->get_data();
$product_id = $item_data['product_id'];
# Targeting a defined product ID
if ( $product_id == 326 ) {
// do something
}
}
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works for WooCommerce version 3+
Reference: How to get WooCommerce order details
I was not satisfied with current answers, as sometimes you need to check multiple products. If you do the same search for each product, it's really a waste, so I put it into a dispatcher format.
add_action('woocommerce_order_status_completed', 'onItemCheckout',10,1);
function onItemCheckout($order_id){
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_key => $item_values){
$product_id = $item_values->get_product_id();
switch($item_values->get_product_id()){
case 9999 : FreeShipping($order, $product_id); break;
case 1010 : RequireValidation($order, $product_id); break;
default: break;
}
}
}
Alternatively,...
$ItemCheckoutHandler=[];
$ItemCheckoutHandler[9999]='FreeShipping';
$ItemCheckoutHandler[1010]='RequireValidation';
add_action('woocommerce_order_status_completed', 'onItemCheckout',10,1);
function onItemCheckout($order_id){
global $ItemCheckoutHandler;
$order = wc_get_order($order_id);
foreach ($order->get_items() as $item_key => $item_values){
$product_id=$item_values->get_product_id();
$ItemCheckoutHandler[ $product_id ]( $order, $product_id );
} //Call the function assigned to that product id in the array
}
In either case, the assigned functions would take the order object, rather than the id, and the product_id as an argument:
function FreeShipping($order, $product_id){ ... }
function RequireValidation($order, $product_id){ ... }
You can of course customize these inputs to your liking.
Try this, hope it will work
add_action( 'woocommerce_thankyou', 'your_function_name', 10);
function your_function_name($order_id)
{
$order = wc_get_order($order_id);
foreach($order->get_items() as $order_key => $order_value)
{
$product_id = $order_value->get_data()['product_id'];
if($product_id == '123')
{
//do what you wnat and 123 is random product id, you can match product id with other as you want
}
}
}
Thank you.

Categories