Get Woocommerce last order id from database using php - 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

Related

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.

Using wc_get_product() with a PHP variable for product ID

I'm building out custom landing pages for products in WooCommerce and I'd like to get the product price amongst other things in order to display them on the landing page.
Each landing page has some custom fields which allow the WP Admin to add in content, for the landing page as well as the product ID, which will then be used to generate the product price, checkout URL etc..
I can't get the wc_get_product(); to work with my custom field or a variable built off that. It only works when I use a straight ID. I think there's something I'm not understanding about how variables work within PHP. Here's my code.
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// This line is where the problem is...
$_product = wc_get_product('$courseID');
// If I replace the line above with this line
// $_product = wc_get_product('7217');
// everything works great, but that does not let
// each landing page function based on the custom fields where the user determines
// the product ID they are selling on that landing page.
// Get's the price of the product
$course_price = $_product->get_regular_price();
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
Update
I get the following error using wc_get_product( $courseID ); or get_product( $courseID );:
Fatal error: Call to a member function get_regular_price() on a non-object in ...
Update related to your recent comment. The 2 ways to explore:
1) Instead of you should try to use to get the product object (avoiding the error):
$courseID = the_field('course_id');
// Optionally try this (uncommenting)
// $courseID = (int)$courseID;
// Get an instance of the product object
$_product = new WC_Product($courseID);
2) Alternatively if this doesn't work, you should try to use get_post_meta() function to get the product price (or any product meta data) this way:
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// Get the product price (from this course ID):
$course_price = get_post_meta($courseID, '_regular_price', true);
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
This time you should get displayed the price with one or the other solutions.
Update: May be Also you need to convert $courseID to an integer variable.
Because you need to use your variable $courseID inside wc_get_product() (without the 2 ') function this way:
<?php
//Gets the course ID from the custom field entered by user
$courseID = the_field('course_id');
// Optionally try this (uncommenting)
// $courseID = (int)$courseID;
// Here
$_product = wc_get_product( $courseID );
$course_price = $_product->get_regular_price();
// Output the Course price
?> <span class="coursePrice">$<?php echo $course_price;?></span>
This should work now.
You can try this out :
$courseID = the_field('course_id');
$product = get_product( $courseID );
I figured out the answer after running through the possible solution routes that #LoicTheAztec supplied in his response. None of these worked and so I assumed something else was up.
I use Advanced Custom Fields to add custom fields in the back end and I was using ACF's the_field() in order to create my variable. That is incorrect usage of that function as it's designed to display the field, (it's basically using php's echo). To work with these custom field's you need to use ACf's get_field() which is to use it to store a value, echo a value and interact with a value.
Once I switched to setting my $courseID to this..
$courseID = get_field('course_id');
Everything worked. My code worked, and all #LoicTheAztec's code approaches also worked.

Magento/PHP - How to get custom customer attribute in order

i am using Magento 1.9.0.1 and i am developing a custom extension.
Right now i am stuck at the following thing.
Like this i use to get the customers name from an order:
$CustomerName = $observer->getOrder()->getBillingAddress()->getName();
I have custom customer attribute called sms_on_order_change and i am trying to get the value of it like that:
$SMSOnStatusChange = $observer->getResource()->getAttribute('sms_on_order_change')->getFrontend()->getValue();
But it is not working.
Here is the extension that i am using for the creation of custom customer attributes: http://www.magentocommerce.com/magento-connect/manage-customer-attributes.html
So guys, can you help me out so i can get the value of this custom attribute ?
Thanks in advance!
This should help you out:
//get order from observer
$order = $observer->getOrder();
// get customer id from order
$customer_id = $order->getCustomerId();
// condition only necessary if guest orders are allowed
if ($customer_id)
{
$_customer = Mage::getModel('customer/customer')->load($customer_id);
$sms_on_order_change = $_customer->getData('sms_on_order_change');
}

Update custom fields value in magento cart

Need to update custom field value in magento order where order_date is my custom field.
$order2 = Mage::getModel('sales/order')->load(100000013);
It returns following exception Call to a member function getMethodInstance() on a non-object.
Any solution for fix this issue ?
Your order not able to load by magento that's why magento giving you error.
you are passing order increment id in the load function
Load By Increment Id
$id = 100000013;
$order = Mage::getModel('sales/order')->loadByIncrementId($id);
$order->setData('order_date', "2014-12-12");
$order->save();
Load By Order Id(Entity Id)
$id = 13;
$order = Mage::getModel('sales/order')->load($id);
$order->setData('order_date', "2014-12-12");
$order->save();
Please check.

How to retrieve bought items information inside an order

I want to send a weekly reminder email to customers who have bought something but not paid yet.
Using this script I can show an order:
<?php
//from http://www.exploremagento.com/magento/run-magento-code-outside-of-magento.php
require_once '../app/Mage.php';
umask(0);
Mage::app('default');
$orders = Mage::getModel('sales/order')->getCollection()
->setOrder('increment_id','DESC')
->setPageSize(1)
->setCurPage(1);
$LastOrderNr = $orders->getFirstItem()->getIncrementId() - 100000000;
$LastOrderNr=494;
$order = Mage::getModel('sales/order')->load($LastOrderNr); //put a valid order entity_id there;
print_r($order->debug());
echo "<br/>******************************<br/>";
?>
I can retrieve several useful info-blocks (i.e. customer's email address, total amount) but it won't show the items they have bought. How/where can I retrieve that kind of information?
In Magento ordered products called 'order items'. You can get order items data like this:
`
// 1. get order. you can load it by order entity id (f.e. 494)
$order = Mage::getModel('sales/order')->load($orderId);
// or by order increment id (100000494)
$order = Mage::getModel('sales/order')->loadByIncrementId($incrementId);
// 2. get order items collection
foreach ($order->getItemsCollection() as $item) {
Zend_Debug::dump($item->getData());
}
`
it can be much easier to get the last Order , especialy needed for the success Site
$order = Mage::getModel('sales/order')->load(Mage::getModel('sales/order')->getCollection()->getLastItem()->getEntityId());
Example: Last Order Costs
$grand_total = Mage::getModel('sales/order')->load(Mage::getModel('sales/order')->getCollection()->getLastItem()->getEntityId())->getGrandTotal();

Categories