更新所有 WooCommerce 处理订单中的 ACF 字段

Update an ACF field in all WooCommerce processing orders

objective get/query/loop 遍历所有 order_status“正在处理”的订单,如果没有延期交货的商品,则更新高级自定义字段 'internal_status' 到值 'Ready to Pack'

现在测试一种方法(为了保持简单,看看它是否有效)我只是想在订单传递到状态“已完成”时更新自定义字段(没有条件“延期交货的项目” “还)

基于 答案代码,这是我的代码尝试:

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 );

}

我知道我在这里没有完全掌握的一件事是查询/获取“处理状态”上的所有订单并更新其相应字段的方法。

您应该尝试使用以下轻量级有效的方法 (使用使用 WPDB SQL 查询的自定义函数,查询所有未延期交货的订单 ID ):

/*
 * Custom function that query all orders without backordered items
 *
 * @param  bool|string $status  Order status can be defined (optional)
 * @return array
 */
function get_orders_ids_without_backordered_items( $status = false ) {
    global $wpdb;

    $post_status_query = $status ? "AND p.post_status = 'wc-" . str_replace('wc-', '', $status) . "'" : '';

    return (array) $wpdb->get_col( "
        SELECT p.ID
        FROM {$wpdb->prefix}posts p
        WHERE p.ID NOT IN (
            SELECT DISTINCT oi.order_id FROM {$wpdb->prefix}woocommerce_order_items oi
            INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta oim ON oi.order_item_id = oim.order_item_id
            WHERE oim.meta_key = 'Backordered'
        ) $post_status_query
    " );
}

// Update ACF 'internal_status' custom field on processing orders.
add_action( 'woocommerce_order_status_completed', 'auto_update_orders_internal_status', 10, 2 ); // Optional (to be removed if not necessary)
add_action( 'woocommerce_order_status_processing', 'auto_update_orders_internal_status', 10, 2 );
function auto_update_orders_internal_status( $order_id, $order ){
     // Get all "processing" orders without backordered items
    $orders_ids = get_orders_ids_without_backordered_items( 'processing' );
    if( ! empty($orders_ids) ) {
        foreach($orders_ids as $post_id) {
            $acf_value = 'Ready to Pack';
            if ( get_field( 'internal_status', $post_id ) !== $acf_value ) {
                update_field( 'internal_status', $acf_value, $post_id ); 
            }
        }
    }
}

代码进入活动子主题(或活动主题)的 functions.php 文件。第一个功能已经过测试并且可以工作。第二个函数不会抛出任何错误。

相关: