John Davidson

php - Update an ACF field in all WooCommerce processing orders

0 comments
Message:


The objective is to get/query/loop through all orders which have order_status "Processing", and if they have no items in backorder, update an advanced custom field 'internal_status' to value 'Ready to Pack'


Right now for a method of testing (to keep it simple and see if it's working) I am just trying to update the custom field whenever an order is passed to status "Completed" (no condition for "items in backorder" yet)


Based on Auto completed status for all existing processing orders in WooCommerce answer code, here is my code attempt:


function auto_update_orders_internal_status(){
// Get all current "processing" customer orders
$processing_orders = wc_get_orders( $args = array(
'numberposts' => -1,
'post_status' => 'wc-processing',
) );
if(!empty($processing_orders))
foreach($processing_orders as $order)

add_action('acf/save_post', 'update_internal_status_ready_to_pack');

}

add_action( 'woocommerce_order_status_completed', 'auto_update_orders_internal_status' );



function update_internal_status_ready_to_pack ( $order_id ) {

$internalstatus = 'Ready to Pack';
update_field( 'internal_status', $internalstatus, $order_id );

}

One thing I am aware I don't fully grasp here is the method of querying / getting all orders on "Processing status" and updating their corresponding fields.



My Answer:
'processing' in WooCommerce and update a specific ACF field for each order.

Here is an example code snippet to achieve this:

php
// Get all processing orders in WooCommerce
$processing_orders = wc_get_orders( array(
'status' => 'processing',
'limit' => -1, // Get all orders
) );

// Loop through each processing order
foreach ( $processing_orders as $order ) {
// Get the order ID
$order_id = $order->get_id();

// Update the ACF field for the order
update_field( 'your_acf_field_key', 'new_value', 'order_' . $order_id );
}


In this code snippet:
1. We first use the `wc_get_orders` function to get all orders with the status 'processing'.
2. We then loop through each order and get the order ID.
3. We use the `update_field` function from ACF to update the specific ACF field for each order. Replace `'your_acf_field_key'` with the key of the ACF field you want to update and `'new_value'` with the new value you want to set for that field.

Make sure to replace `'your_acf_field_key'` with the actual key of the ACF field you want to update. You can find the key of the ACF field in the ACF settings in the WordPress admin panel.

Also, make sure to test this code on a staging site before running it on a live site to avoid any unintended consequences.

Rate this post

4 of 5 based on 1946 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us