Change WooCommerce order status based on approved status and specific order item

帅比萌擦擦* 提交于 2021-01-28 03:20:44

问题


I try to change a WooCommerce order status to "Processing" when the current status is "Approved" and the order includes a specific product ( id = 10).

I have attempted the code below but it is not working. I am quite new to php and would appreciate any guidance!

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

        }

    }
}

回答1:


  • woocommerce_order_status_changed has 4 parameters
  • This line -> if ($product_id!="10") says NOT equal, you also compare with a string and not with a numerical value

Try it this way

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


来源:https://stackoverflow.com/questions/62049612/change-woocommerce-order-status-based-on-approved-status-and-specific-order-item

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!