Woocommerce | Export Order Items to JSON | External API - php

Scenraio: using woocommerce and am required to serialize the order object and send to external api.
Issue: Unable to get the JSON of items in the order.
$order = new WC_Order( $order_id );
$items = $order->get_items();
I tried the following:
The implode($items); method returns the JSON but it has escaped quotes and does not separate the array items by a ",".
Tried foreach on $items to add each item to another array array_push($order_items,$item); but json_encode($order_items); return an array of nulls
Is there a way to inspect each property of the $item and assign it to a custom object, create an array and the serialize the same array?
PHP NOOB.

Related

Is file_put_contents a reliable way to check value of some variables?

My website is built with wordpress+woocommerce.
For learning purpose, I am trying to check an order's detail once it is completed using file_put_contents. Here is the code:
add_action( 'woocommerce_order_status_completed', 'change_role_on_first_purchase' );
function change_role_on_first_purchase( $order_id ) {
$order = new WC_Order( $order_id );
// $user = new WP_user($order->user_id);
file_put_contents('order.json',json_encode($order));
file_put_contents('userid.json',json_encode($order->user_id));
}
}
While the second file_put_contents does write the correct user ID into userid.json, order.json's content is just {}. Obviously $order is not empty, then why file_put_contents is outputting an empty json object?
Short Answer
Before you can json_encode($order), you need to get the order's data as a plain unprotected array:
$order = new WC_Order( $order_id );
$order_data = $order->get_data(); // ADD THIS
file_put_contents('order.json',json_encode($order_data));
Long Answer
Read: json_encode empty with no error
TLDR: Basically, json_encode works best when an object has public properties. WC_Order doesn't have any, so it results in an empty object and that's why they created the get_data() method (to expose the data as a plain "unprotected" associative array) (perfect food for json_encode).

Get Woocommerce last order id from database using php

In Woocommerce, I am trying to get the last order id using the following code:
<?php $order = new WC_Order($post->ID);echo $order->id;//to escape # from order id $order_id = trim(str_replace('#', '', $order->get_order_number())); ?>
But it doesn't work as I am getting a zero value.
The purpose is to add 1 to this last order ID, to get the new usable order ID.
Any help is appreciated.
It seems that you would like to get the next usable POST ID (Order Id), to save it, for example, as new Order in database with some related data.
This is absolutely not the way to do it and you need to think it different... Now you can use one of the 3 following ways:
Using the WordPress dedicated function wp_insert_post() that returns the post ID (Order ID).
Using the Woocommerce dedicated function wc_create_order() that returns the WC_Order Object.
Then from the the order object, you can get the order ID using $order->get_id().
Using the Woocommerce empty WC_Order object instance and the save() method:
// Get an empty instance of the `WC_Order` Object
$order = new WC_Order();
// Save the order to the database
$order->save();
// Get the Order ID
$order_id = $order->get_id();
Addition - Get the last Order ID in Woocommerce:
To get and display the last order ID in woocommerce use a WC_Order_Query in this two simple line:
<?php
$last_order_id = wc_get_orders(array('limit' => 1, 'return' => 'ids')); // Get last Order ID (array)
echo (string) reset($last_order_id); // Displaying last order ID
?>
Tested and works

$Order ACCESSING PROTECTED ARRAY

I am attempting to access the meta data in an $order through a woocommerce order system. The system has extra order fields . It is these fields I am attempting to acess. Every variation I try, just end up with with a server error OR the data is blank on output. I have tried $MetaData->id, $MetaData[0]['id'], using a foreach loop for each record...etc etc. It makes no difference, the data, in string form, does not display. I suspect it has something to do with it being a protected array, which I have no clue as to how to manage...obviously. It is not working.
Here is the code and the some results of the test.
$order = new WC_Order( $order_id );
$order_data = $order->get_data();
$MetaData = $order_data['meta_data'];
DebugLog(json_encode($MetaData));
// OUTPUT of JSON_ENCODE:
// [{"id":2658,"key":"business-name","value":"BUSINESS NAME HERE"},{"id":2659,"key":"full-business-address","value":"1028 STREET Dr"},{"id":2660,"key":"city","value":"CITY NAME"},{"id":2661,"key":"state","value":"California"},{"id":2662,"key":"zip","value":"900XX"},{"id":2663,"key":"_subscription_switch_data","value":[]},{"id":2723,"key":"_stripe_customer_id","value":"XXXX"},{"id":2724,"key":"_stripe_source_id","value":"XXXX"},{"id":2727,"key":"_stripe_charge_captured","value":"yes"},{"id":2728,"key":"_stripe_fee","value":"0.45"},{"id":2729,"key":"_stripe_net","value":"4.55"},{"id":2730,"key":"_stripe_currency","value":"USD"},{"id":2736,"key":"_wc_memberships_access_granted","value":{"215":{"already_granted":"yes","granting_order_status":"processing"}}},{"id":2748,"key":"_wc_memberships_access_granted","value":{"215":{"already_granted":"yes","granting_order_status":"processing"}}}]
foreach($MetaData as $index => $feature)
{
$MetaValue = $MetaData[$index ]['key'];
DebugLog($MetaValue);
}
The final foreach causes a server error. I just don't see it and I have tried all sorts of combinations.
I have also tried:
foreach($MetaData as $feature)
{
$MetaValue = $feature['key'];
DebugLog($MetaValue);
}
and
$MetaValue = $MetaData[0]['key']
Same results. Any idea? What am I missing in this most basic of programming tools?
UPDATE! GOT IT
Wild ride. You have to create the pointer to the row (MetaData, but then treat each row as it's own array with indexes.
THE SOLUTION
$order = new WC_Order( $order_id );
$order_data = $order->get_data();
$MetaData = $order_data['meta_data'];
foreach($MetaData as $SubRow)
{
DebugLog($SubRow->id);
DebugLog($SubRow->key);
DebugLog($SubRow->value);
}
Thanks to all who wrote and got me to think out of the box a bit.

Get all WooCommerce subscriptions

I a need to create a wordpress template to collect all Woocommerce subscriptions, but I'm having trouble with the documentation. I need to know which files to import and which function to call.
Thank you in advice.
Update - You can use multiple ways:
1) The built in function wcs_get_subscriptions() which accepts specific arguments. In your case, to get all subscriptions, you will use:
$subscriptions = wcs_get_subscriptions(['subscriptions_per_page' => -1]);
You will get an array of Subscription protected objects where you can use on each object the WC_Data get_data() method, to access the data:
$subscriptions = wcs_get_subscriptions(['subscriptions_per_page' => -1]);
// Loop through subscriptions protected objects
foreach ( $subscriptions as $subscription ) {
// Unprotected data in an accessible array
$data = $subscription->get_data();
print_r( $data ); // Display the subscription raw data array
}
Related: Get Subscription Product author of a Woocommerce subscription
2) You can also use a SQL query to get all subscriptions
A SQL query can be lighter and allows more filtering. This way you can get only the required data in a more effective way.
As subscriptions are a Wordpress custom post type, You can get all subscriptions IDs first. Then in a foreach loop you will be able to get the WC_subscription object.
global $wpdb;
// get all subscriptions IDS
$subscriptions_ids = $wpdb->get_col("
SELECT ID FROM {$wpdb->prefix}posts
WHERE post_type LIKE 'shop_subscription'
");
// Loop through subscriptions Ids
foreach($subscriptions_ids as $subscription_id){
// Get an instance of the WC_Subscription object
$subscription = new WC_Subscription( $subscription_id );
$data = $subscriptions->get_data();
print_r( $data ); Display the subscription raw data (unprotected accessible array)
}
Then with the $subscription object and the $subscription_id you will be able to do what you want, using WC_Subscription methods to get the desired data or the using subscription ID on dedicated functions.
Official developer Documentation:
Introduction to Subscriptions Developer Documentation
Subscriptions Data Structures & Storage
You can use the built in function wcs_get_subscriptions($args) and pass the following $args
$args = array( 'subscriptions_per_page' => -1 );
$subscriptions = wcs_get_subscriptions( $args );
You can even filter by subscription status also in the arguments.

How to get woocommerce cart item names as array

I was wondering how to get all the items in my cart as an array.
I need this because I have to use array_intersect, this way I can compare them.
I haven't found anything about this on the internet.
You can access the cart contents through the WC()->cart object, like so:
<?php
$cart_contents = WC()->cart->cart_contents;
$cart_item_names = array();
foreach($cart_contents as $item) {
array_push($cart_item_names, $item['data']->post->post_title);
}

Categories