【问题标题】:Change WooCommerce order status based on approved status and specific order item根据批准状态和特定订单项目更改 WooCommerce 订单状态
【发布时间】:2020-05-27 17:47:21
【问题描述】:

当当前状态为“已批准”且订单包含特定产品 (id = 10) 时,我尝试将 WooCommerce 订单状态更改为“处理中”。

我尝试了下面的代码,但它不起作用。我对 php 很陌生,希望得到任何指导!

add_action('woocommerce_order_status_changed', 'ts_auto_complete_business_cards');

function ts_auto_complete_business_cards($order_id)
{

    if ( ! $order_id ) {
        return;
    }

    global $product;
    $order = wc_get_order( $order_id );

    if ($order->data['status'] == 'approved') {
        $items=$order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item->get_product_id();
            if ($product_id!="10")
            {
                $order->update_status( 'completed' );
            }

        }

    }
}

【问题讨论】:

    标签: php wordpress woocommerce hook-woocommerce orders


    【解决方案1】:
    • woocommerce_order_status_changed有4个参数
    • 这一行 -> if ($product_id!="10") 表示不等于,您还与字符串而不是数值进行比较

    试试这个方法

    function action_woocommerce_order_status_changed( $order_id, $old_status, $new_status, $order ) {
    
        // Compare
        if( $old_status === 'approved' ) {
            // Get items
            $items = $order->get_items();
    
            foreach ( $items as $item ) {
                // Get product id
                $product_id = $item->get_product_id();
    
                if ($product_id == 10 ) {
                    $order->update_status( 'processing' );
                    break;
                }
            }
        }
    }
    add_action( 'woocommerce_order_status_changed', 'action_woocommerce_order_status_changed', 10, 4 );
    

    【讨论】:

    • 感谢您的回复!我尝试了您的建议,但不幸的是它不起作用(我认为我正在使用的插件与此有关)。但是,根据您对我的错误的解释,我将代码从 if ($product_id!="10") 更正为 if ($product_id==10) 并且效果很好。谢谢!
    猜你喜欢
    • 2022-10-05
    • 2017-05-24
    • 2021-04-08
    • 2018-01-01
    • 2019-08-23
    • 2021-06-02
    • 2019-04-24
    • 2018-08-30
    • 1970-01-01
    相关资源
    最近更新 更多