在 WooCommerce 中保存订单后保存自定义项目元数据

Save custom item meta data once order has been saved in WooCommerce

我正在使用 save_post_{$post->post_type} 挂钩,它会在 post(订单)被保存后触发。

目的是根据某些订单状态保存产品元数据。这是我 wrote/used 为此的代码:

add_action ( 'save_post_shop_order', function (int $postId, \WP_Post $post, bool $update): void   {

        
    $order = new WC_Order( $postId );
    
    $order_status = $order->get_status();
    $status_arrays = array( 'processing', 'on-hold', 'to-order', 'needed' );
    
    if ( in_array($order_status, $status_arrays) ) {
        return;
    }
        
    $items = $order->get_items();
    
     foreach ( $items as $item ) {
        $product_id = $item->get_product_id();
        $product    = wc_get_product( $product_id );
        $final_product->update_meta_data( '_test', '_test' );
        $final_product->save();

    }

   },
    10,
    3
);

但是,我在我的数据库中找不到新的元数据。有什么建议吗?谁能帮我实现这个目标?

您的代码包含一些错误,例如 $final_product 不等于 $product,因此未定义。

这应该足够了:(通过注释标签进行解释,添加到代码中)

function action_save_post_shop_order( $post_id, $post, $update ) {
    // Checking that is not an autosave && current user has the specified capability
    if ( ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) || ! current_user_can( 'edit_shop_order', $post_id ) ) {
        return;
    }
    
    // Get $order object
    $order = wc_get_order( $post_id );

    // Is a WC_Order
    if ( is_a( $order, 'WC_Order' ) ) {
        // NOT has status
        if ( ! $order->has_status( array( 'processing', 'on-hold', 'to-order', 'needed' ) ) ) { 
            // Loop through order items
            foreach( $order->get_items() as $item ) {
                // Get an instance of corresponding the WC_Product object
                $product = $item->get_product();
                
                // Meta: key - value
                $product->update_meta_data( '_test', '_test' );
                
                // Save
                $product->save();
            }
        }
    }
}
add_action( 'save_post_shop_order', 'action_save_post_shop_order', 10, 3 );

注意:如果订单应该有某个状态没有状态,只需删除 ! 来自:

// NOT has status
if ( ! $order->has_status(..