How to get all order details in wordpress/woocommerce? [duplicate] - php

This question already has answers here:
How to get WooCommerce order details
(6 answers)
Closed 4 years ago.
I am using woo-commerce and trying to get all the order details from database.I am new to it and cant make it happened.I have already created order_details.php template where I can get all orders data.
Can anyone help me out?

Try This Code.
$args = array(
'post_type' => 'shop_order',
'posts_per_page' => '-1'
);
$my_query = new WP_Query($args);
$orders = $my_query->posts;
echo "</pre>";
print_r($orders);
echo "<pre>";
Customize As par Ur Requerment.

$my_course_query = new WP_Query(array('post_type'=>'shop_order','post_status'=>'wc-completed'));
Change status to woocoommerce status

Since Woocommerce mega major Update 3.0+ things have changed quite a lot:
WC_Order properties can't be access directly as before and will throw some errors.
New WC_Order and WC_Abstract_Order getters and setters methods are now needed.
There is some New classes for Order items:
WC_Order_Item class.
WC_Order_Item_Product class.
So also the Order items properties will not be accessible as before in a foreach loop and you will have to use this specific getter and setter methods instead
// Get an instance of the WC_Order object (same as before)
$order = wc_get_order( $order_id );
// Get the order ID
$order_id = $order->get_id();
// Get the custumer ID
$order_id = $order->get_user_id();
Get and access to the order data properties (in an array of values):
$order = wc_get_order( $order_id );
$order_data = $order->get_data(); // The Order data
$order_id = $order_data['id'];
$order_parent_id = $order_data['parent_id'];
$order_status = $order_data['status'];
$order_currency = $order_data['currency'];
$order_version = $order_data['version'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method_title = $order_data['payment_method_title'];
$order_payment_method = $order_data['payment_method'];
$order_payment_method = $order_data['payment_method'];
## Creation and modified WC_DateTime Object date string ##
// Using a formated date ( with php date() function as method)
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_date_modified = $order_data['date_modified']->date('Y-m-d H:i:s');
// Using a timestamp ( with php getTimestamp() function as method)
$order_timestamp_created = $order_data['date_created']->getTimestamp();
$order_timestamp_modified = $order_data['date_modified']->getTimestamp();
$order_discount_total = $order_data['discount_total'];
$order_discount_tax = $order_data['discount_tax'];
$order_shipping_total = $order_data['shipping_total'];
$order_shipping_tax = $order_data['shipping_tax'];
$order_total = $order_data['cart_tax'];
$order_total_tax = $order_data['total_tax'];
$order_customer_id = $order_data['customer_id']; // ... and so on
## BILLING INFORMATION:
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
$order_billing_company = $order_data['billing']['company'];
$order_billing_address_1 = $order_data['billing']['address_1'];
$order_billing_address_2 = $order_data['billing']['address_2'];
$order_billing_city = $order_data['billing']['city'];
$order_billing_state = $order_data['billing']['state'];
$order_billing_postcode = $order_data['billing']['postcode'];
$order_billing_country = $order_data['billing']['country'];
$order_billing_email = $order_data['billing']['email'];
$order_billing_phone = $order_data['billing']['phone'];
## SHIPPING INFORMATION:
$order_shipping_first_name = $order_data['shipping']['first_name'];
$order_shipping_last_name = $order_data['shipping']['last_name'];
$order_shipping_company = $order_data['shipping']['company'];
$order_shipping_address_1 = $order_data['shipping']['address_1'];
$order_shipping_address_2 = $order_data['shipping']['address_2'];
$order_shipping_city = $order_data['shipping']['city'];
$order_shipping_state = $order_data['shipping']['state'];
$order_shipping_postcode = $order_data['shipping']['postcode'];
$order_shipping_country = $order_data['shipping']['country'];
Get the order items and access the data with WC_Order_Item_Product and WC_Order_Item methods:
$order = wc_get_order($order_id);
// Iterating through each WC_Order_Item_Product objects
foreach ($order->get_items() as $item_key => $item_values):
## Using WC_Order_Item methods ##
// Item ID is directly accessible from the $item_key in the foreach loop or
$item_id = $item_values->get_id();
## Using WC_Order_Item_Product methods ##
$item_name = $item_values->get_name(); // Name of the product
$item_type = $item_values->get_type(); // Type of the order item ("line_item")
$product_id = $item_values->get_product_id(); // the Product id
$wc_product = $item_values->get_product(); // the WC_Product object
## Access Order Items data properties (in an array of values) ##
$item_data = $item_values->get_data();
$product_name = $item_data['name'];
$product_id = $item_data['product_id'];
$variation_id = $item_data['variation_id'];
$quantity = $item_data['quantity'];
$tax_class = $item_data['tax_class'];
$line_subtotal = $item_data['subtotal'];
$line_subtotal_tax = $item_data['subtotal_tax'];
$line_total = $item_data['total'];
$line_total_tax = $item_data['total_tax'];
endforeach;

You can user below code
require(dirname(__FILE__) . '/wp-load.php');
global $wpdb;
$orders = get_posts( array(
'post_type' => 'shop_order',
'posts_per_page' => '-1'
) );
You need to include wp-load.php file
require(dirname(__FILE__) . '/wp-load.php');
and add global variable as global $wpdb; before this code.

Related

how i can retrieve all woocommerce orders in new custom plugin

i'm creating a new custom plugin and need to retrieve all woocommerce orders
i tried to use : wc_get_orders() function to retrieve all woocommerce orders but i got
Uncaught Error: Call to undefined function wc_get_orders()
and did this :
require_once '../woocommerce/includes/wc-order-functions.php';
but i got :
require_once(../woocommerce/includes/wc-order-functions.php): failed to open stream:
how i can retrieve all woocommerce orders
WooCommerce already provided API to get all orders https://example.com/wp-json/wc/v3/orders
For more details please see the documentation
If you want function based instead of REST API then, please do like this:
You should call your order function into the action hook woocommerce_after_register_post_type to work properly. So please enclose your function call like this:
add_action(
'woocommerce_after_register_post_type',
function() {
$orders = wc_get_orders( array( 'numberposts' => -1 ) );
var_dump( $orders );
}
);
Then you can loop through the object and fetch all the necessary details for e.g.
foreach ( $orders->get_items() as $item_id => $item ) {
$product_id = $item->get_product_id();
$variation_id = $item->get_variation_id();
$product = $item->get_product();
$name = $item->get_name();
$quantity = $item->get_quantity();
$subtotal = $item->get_subtotal();
$total = $item->get_total();
$tax = $item->get_subtotal_tax();
$taxclass = $item->get_tax_class();
$taxstat = $item->get_tax_status();
$allmeta = $item->get_meta_data();
$somemeta = $item->get_meta( '_whatever', true );
$type = $item->get_type();
}
For more details please check this article.

Webhook triggers product insert on billing program with Woocommerce product details

I've been asked to create a self made plugin that consists on whenever a product is created on woocommerce it gets this product details and send them to the billing program,
From Automatic product insert via soap on WooCommerce product creation answer code to my previous question, I am using the following code :
add_action( 'woocommerce_new_product', 'woocommerce_create_product_callbback', 10, 4 );
function woocommerce_create_product_callbback( $product_id ) {
$WS_URL =''; //billing program url
$API_KEY = ''; //billing program API Key
$soap = '';
$APISession = '';
// Connect
$result = $soap->authenticate( $API_KEY );
$APISession = $result[1];
if( $APISession ) {
// Get_the WC_Product Object
$product = wc_get_product( $product_id );
// Product data
$status = $product->get_status();
$name = $product->get_name();
$description = $product->get_description();
$short_descr = $product->get_short_description();
$parent_id = $product->get_parent_id();
$menu_order = $product->get_menu_order();
$date_created = $product->get_date_created()->getOffsetTimestamp();
$date_created_gmt = $product->get_date_created()->getTimestamp();
$slug = $product->get_slug();
$author_id = get_post_field ('post_author', $product_id);
// Product meta data (and post terms)
$type = $product->get_type();
$tax_class = $product->get_tax_class();
$stock_status = $product->get_stock_status();
$price = $product->get_price();
$sku = $product->get_sku();
// Special
$active = $product->get_status() ==='publish' ? '1' : '0';
$hasStocks = $product->is_in_stock() ? '1' : '0';
// Undefined (not defined in WooCommerce
$shortName = '';
$tax = '';
$obs = '';
$isService = '0';
$vendorRef = ''; // May be the author ID
$ean = ''; // May be the SKU
// Send data and insert product
$product = $soap->insertProduct( $APISession, $ref, $designation, $shortName, $tax, $obs, $isService, $hasStocks, $active, $shortDesc, $longDesc, $price, $vendorRef, $ean);
}
}
but this catches me the following error :
Uncaught Error: Call to undefined function wc_get_product()
Hope someone can help me
IMPORTANT: First you need to solve the "Fatal Error Call to a member function authenticate()" as this is related to your SOAP initialization, because $soap = ''; requires to be an object and not an empty string. That's why you get this error on the answer from Dmitry.
This problem can't not be handled by anyone as you doesn't give any related details or documentation (and this has nothing to do with a WooCommerce tagged question as It's related to PHP and SOAP first).
Once The SOAP issue will be solved, try the following using woocommerce_admin_process_product_object dedicated action hook (where the WC_Product Object is already defined as an argument in the function:
add_action( 'woocommerce_admin_process_product_object', 'wc_admin_process_product_object_action_callbback', 900, 1 );
function wc_admin_process_product_object_action_callbback( $product ) {
// On product creation and product has not been processed yet
if ( ! $product->get_meta('_soap_prodcessed' ) {
$WS_URL =''; //billing program url
$API_KEY = ''; //billing program API Key
$soap = '';
$APISession = '';
// Connect
$result = $soap->authenticate( $API_KEY );
$APISession = $result[1];
if( $APISession ) {
// Get Product data
$status = $product->get_status();
$name = $product->get_name();
$description = $product->get_description();
$short_descr = $product->get_short_description();
$parent_id = $product->get_parent_id();
$menu_order = $product->get_menu_order();
$date_created = $product->get_date_created()->getOffsetTimestamp();
$date_created_gmt = $product->get_date_created()->getTimestamp();
$slug = $product->get_slug();
$author_id = get_post_field ('post_author', $product_id);
// Product meta data (and post terms)
$type = $product->get_type();
$tax_class = $product->get_tax_class();
$stock_status = $product->get_stock_status();
$price = $product->get_price();
$sku = $product->get_sku();
// Special
$active = $product->get_status() ==='publish' ? '1' : '0';
$hasStocks = $product->is_in_stock() ? '1' : '0';
// Undefined (not defined in WooCommerce
$shortName = '';
$tax = '';
$obs = '';
$isService = '0';
$vendorRef = ''; // May be the author ID
$ean = ''; // May be the SKU
// Send data
$result = $soap->insertProduct( $APISession, $ref, $designation, $shortName, $tax, $obs, $isService, $hasStocks, $active, $shortDesc, $longDesc, $price, $vendorRef, $ean);
// Add custom meta to flag the product as processed via soap (avoid multiple insertions)
$product->update_meta_data( '_soap_prodcessed', '1' );
}
}
}
Code goes in functions.php file of your active child theme (or active theme). It could works once you will solve the SOAP issue.
I think you should use another hook transition_post_status:
function woocommerce_create_product_callbback( $new_status, $old_status, $post ) {
if (
$old_status != 'publish' &&
$new_status == 'publish' &&
!empty( $post->ID ) &&
in_array( $post->post_type, array( 'product') ) )
{
$product = wc_get_product( $post->ID );
$WS_URL =''; //billing program url
$API_KEY = ''; //billing program API Key
$soap = '';
$APISession = '';
// Connect
$result = $soap->authenticate( $API_KEY );
$APISession = $result[1];
if( $APISession ) {
// Product data
$status = $product->get_status();
$name = $product->get_name();
$description = $product->get_description();
$short_descr = $product->get_short_description();
$parent_id = $product->get_parent_id();
$menu_order = $product->get_menu_order();
$date_created = $product->get_date_created()->getOffsetTimestamp();
$date_created_gmt = $product->get_date_created()->getTimestamp();
$slug = $product->get_slug();
$author_id = get_post_field ('post_author', $product_id);
// Product meta data (and post terms)
$type = $product->get_type();
$tax_class = $product->get_tax_class();
$stock_status = $product->get_stock_status();
$price = $product->get_price();
$sku = $product->get_sku();
// Special
$active = $product->get_status() ==='publish' ? '1' : '0';
$hasStocks = $product->is_in_stock() ? '1' : '0';
// Undefined (not defined in WooCommerce
$shortName = '';
$tax = '';
$obs = '';
$isService = '0';
$vendorRef = ''; // May be the author ID
$ean = ''; // May be the SKU
// Send data and insert product
$product = $soap->insertProduct( $APISession, $ref, $designation, $shortName, $tax, $obs, $isService, $hasStocks, $active, $shortDesc, $longDesc, $price, $vendorRef, $ean);
}
}
add_action( 'transition_post_status', 'woocommerce_create_product_callbback', 10, 3 );
it's work fine I checked. Please check the Documentation. Hope help you.

Getting the correct variation price from order items in Woocommerce 3

Im trying to get the correct price for each item variation however it only seems to be getting the first price of that product variation. Not sure how to solve this.
Code:
$query = new WC_Order_Query( array(
'status' => 'on-hold',
'orderby' => 'date',
'order' => 'DESC',
'return' => 'ids',
) );
$order_ids = $query->get_orders();
foreach( $order_ids as $order_id ) {
$order = new WC_Order($order_id);
foreach ($order->get_items() as $item_id => $item_obj) {
$_product = wc_get_product($item_obj['product_id']);
$product = new WC_Product_Variable($item_obj['product_id']);
$product_variations = $product->get_available_variations();
$variation_product_id = $product_variations [0]['variation_id'];
$variation_product = new WC_Product_Variation( $variation_product_id );
$t_dy = $variation_product->get_price();
$item_qty = $item_obj['qty'];
$it_total = $item_qty * $t_dy;
$td = wc_update_order_item_meta($item_id, '_line_total', $it_total);
$order->calculate_totals();
$order->save();
}
}
Updated 3
To get the correct current variation price when the order item is a product variation is much more simple than you are doing. Then you will use Woocommerce 3 CRUD setter and getter methods to set the order item totals, save it and update the order.
The code:
// Loop through order items
foreach ($order->get_items() as $item_id => $item ) {
// Targeting only product variation items
if( $item->get_variation_id() > 0 ){
// Get an instance of the WC_Product_Variation object
$product = $item->get_product();
$price = (float) $product->get_price(); // <=== HERE the variation price
$qty = (int) $item->get_quantity(); // <=== HERE the quantity
// set line totals
$item->set_total( $price * $qty );
$item->set_subtotal( $price * $qty );
$item->save(); // save order item data
}
}
// The following need to be outside the order item loop
$order->calculate_totals(); // Save is included into the method
It should better work this way.
Related:
Get Order items and WC_Order_Item_Product in Woocommerce 3
How to get WooCommerce order details
Found the issue! - it was giving out wrong id
replace:
$variation_product_id = $product_variations [0]['variation_id'];
with this:
$product_variation_id = $item_obj->get_variation_id();
$variation_product_id = $product_variation_id;
$variation_product = new WC_Product_Variation( $variation_product_id );

Woocommerce get order key

I have orders in the format [domain]/checkout/order-received/[order_number]/key=[wc-order-key] - how do I get [wc-order-key]?
So far I've done:
add_action('woocommerce_payment_complete', 'custom_process_order', 10, 1);
function custom_process_order($order_id)
{
$order = new WC_Order( $order_id );
$myuser_id = (int)$order->user_id;
$user_info = get_userdata($myuser_id);
$items = $order->get_items();
foreach ($items as $item)
{
$product_name = $item['name'];
$product_id = $item['product_id'];
$product_variation_id = $item['variation_id'];
$product_description = get_post_meta($item['product_id'])->post_content
}
return $order_id;
}
If i understand correctly, you need get order_key by order_id, is it correct?
If so, you can just use WC_Order property:
$test_order = new WC_Order($order_id);
$test_order_key = $test_order->order_key;
Edited
As mentioned indextwo, since Woo 3.0 there new syntax:
$test_order = wc_get_product($order_id);
$test_order_key = $test_order->get_order_key();
2018 updated answer
As WooCommerce 3 changed how property calls were made, the appropriate way to get the same information is:
$order = wc_get_order($order_id);
// Added a check to make sure it's a real order
if ($order && !is_wp_error($order)) {
$order_key = $order->get_order_key();
}
Note that you can easily do the same in reverse: get an order ID from an order key:
$order_id = wc_get_order_id_by_order_key($order_key);

WC_Order get_items() and their Quantity

I am trying to build an application which texts me my woo commerce order, order items and Quantity,
I am 90% there,
function custom_woocommerce_complete_order_sms( $order_id ) {
global $woocommerce;
if ( !$order_id )
return;
$order = new WC_Order( $order_id );
$product_list = '';
$order_item = $order->get_items();
foreach( $order_item as $product ) {
$prodct_name[] = $product['name'];
}
$product_list = implode( ',\n', $prodct_name );
require "twilio-php-master/Services/Twilio.php";
$AccountSid = "xxxxxxxxx";
$AuthToken = "xxxxxxxxx";
$client = new Services_Twilio($AccountSid, $AuthToken);
$people = array(
"xxxxxxxxxx" => "Me",
);
foreach ($people as $number => $name) {
$sms = $client->account->messages->sendMessage(
"+44xxxxxxxxxx",
// the number we are sending to - Any phone number
$number,
// the sms body
"Hey $name, there is a new Order, the order is, $product_list"
);
}
}
My problem is I do not know how to get the item Quantity , for example my text looks like list, item 1, item 2, item 3, I want it to say item 1 x1, item 2 x2, item3 x3
I did try and dig into the email php file in abstract woo commerce folder to see how they do as they send Quantities in emails but got a little lost
also in the class WC_Abstract_Order the only other thing I could find is get_item_total which returns to the total of all items
From research you can also grab the qty from the order item
$product['qty'];
Therefore , it was simple to loop over and add the quantity to the item name (below)
$product_details = array();
$order_items = $order->get_items();
foreach( $order_items as $product ) {
$product_details[] = $product['name']."x".$product['qty'];
}
$product_list = implode( ',', $product_details );

Categories