1
votes

My current code even though has if statement doesn't follow it and still changes the status to "customstatus" of all the "on-hold" orders. Even though it should only change if the order contains the specific product id. This code also adds custom meta to the user. Not sure what I am doing wrong. Any help would be greatly appreciated.

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']=='on-hold') {
        $items=$order->get_items();
        foreach ( $items as $item ) {
            $product_id = $item->get_product_id();
            if ($product_id!=="193007")
            {
                $current_user = wp_get_current_user();
                $current_user_id = get_current_user_id();
                $order->update_status( 'customstatus' );
                update_user_meta( $current_user_id, 'custommeta', '2' );
            }
        }
    }
}
1

1 Answers

2
votes

There are some mistakes and missing things in your code. Try the following:

add_action('woocommerce_order_status_on-hold', 'auto_complete_business_cards', 10, 2 );
function auto_complete_business_cards( $order_id, $order ) {
    $product_id = 193007;
    $found      = false;
            
    // loop though order status     
    foreach ( $order->get_items() as $item ) {
        if ( $item->get_product_id() !== $product_id) {
            $found = true;
            break;
        }
    }
    
    if ( ! $found ) {
        $order->update_status( 'customstatus' );
        update_user_meta( $order->get_user_id(), 'custommeta', '2' );
    }
}

or also this:

add_action('woocommerce_order_status_changed', 'auto_complete_business_cards', 10 , 4 );
function auto_complete_business_cards( $order_id, $order ) {
    if ($new_status === 'on-hold' ) {
        $product_id = 193007;
        $found      = false;
                
        // loop though order status     
        foreach ( $order->get_items() as $item ) {
            if ( $item->get_product_id() !== $product_id) {
                $found = true;
                break;
            }
        }
        
        if ( ! $found ) {
            $order->update_status( 'customstatus' );
            update_user_meta( $order->get_user_id(), 'custommeta', '2' );
        }
    }
}

Code goes in functions.php file of the active child theme (or active theme). It should better work.