'Change woocommerce status with callable function
This function is made to be called with ajax through a button click to change the woocommerce order status. However I was wondering if this function could just be called as a function itself for example in an if statement. I tried putting the code inside an if statement but failed. The code needs to work after an eForm submission which changes the status of that order_id
function update_order_installer_status() { check_ajax_referer( 'nonce_update_order_installer_status', 'nonce' ); // we are safe now
// Get all customer orders
$customer_orders = get_posts( array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => 'shop_order', // WC orders post type
'post_status' => 'wc-pending' // Only orders with status "pending"
) );
foreach ( $customer_orders as $customer_order ) {
// Updated compatibility with WooCommerce 3+
$order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id;
$order = wc_get_order( $customer_order );
// Iterating through each current customer products bought in the order
foreach ($order->get_items() as $item) {
// WC 3+ compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) )
$product_id = $item['product_id'];
else
$product_id = $item->get_product_id();
// Your condition related to your 2 specific products Ids
if ( in_array( $product_id ) )
$order = new WC_Order($_POST['id']); $order->update_status('wc-completed');
$order->status = wc_get_order_status_name($order->get_status()); wp_send_json($order); } } }
add_action( 'wp_ajax_update_order_installer_status', 'update_order_installer_status' );
add_action( 'wp_ajax_nopriv_update_order_installer_status', 'update_order_installer_status' );
I tried the following:
if($this->form_id="109"){ $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_order', 'post_status' => 'wc-pending' ) ); foreach ( $customer_orders as $customer_order ) { $order_id = method_exists( $order, 'get_id' ) ? $order->get_id() : $order->id; $order = wc_get_order( $customer_order );
// Iterating through each current customer products bought in the order
foreach ($order->get_items() as $item) {
// WC 3+ compatibility
if ( version_compare( WC_VERSION, '3.0', '<' ) )
$product_id = $item['product_id'];
else
$product_id = $item->get_product_id();
// Your condition related to your 2 specific products Ids
if ( in_array( $product_id ) )
$order = new WC_Order($_POST['id']); $order->update_status('wc-completed'); }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
