skip to Main Content

I am trying to make a plugin for woocommerce that, at each new order, take all the data that I need, split it by item in a foreach loop and then send each item data as a separate post through cURL. But my code don’t seem to ignore the foreach loop. Here is the code for my loop:

add_action('woocommerce_new_order', 'wdm_send_order_to_ext'); 
function wdm_send_order_to_ext( $order_id ){

    // get order object and order details
    $order = wc_get_order($order_id);

    print_r(" Start ");
    if($order->get_items()>0)
    {
        print_r(" Item exist ");
        foreach($order->get_items() as $item_id => $item_data){
            print_r(" Foreach loop executing for item ID: $item_id ");
        }
    }
    else
    {
        print_r(" No Item ");
    }
    print_r(" End ");
 }

and my result is: Start Item exist End
edit: When i used print_r on $order->get_items(), it printed as
Array
(
)

2

Answers


  1. Chosen as BEST ANSWER

    I finally found my problem: the hook woocommerce_new_order is activated before items are added to the order, instead i used woocommerce_thankyou and it worked.


  2. The quickest way to find out whether you’re able to execute a foreach loop is to strip out everything that isn’t related to the foreach loop, via:

    add_action('woocommerce_new_order', 'wdm_send_order_to_ext'); 
    function wdm_send_order_to_ext( $order_id ){
    
        // get order object and order details
        $order = wc_get_order($order_id);
    
        $endpoint = "https://enwlq927zckka.x.pipedream.net"; 
        foreach($order->get_items() as $item_id => $item_data){
            echo "Foreach loop executing for item ID: $item_id.";
        }
     }
    

    If you’re seeing output, then you know you’re executing the foreach loop. To debug these kinds of things, you need to get comfortable with stripping out the unnecessary and building off of what you can discern one piece at a time.

    One thing you may be encountering (but is outside the scope of the way you worded your question) is that cURL calls can take a very long time to respond. Depending on how your server is configured, it may abort executing the PHP code if it doesn’t finish executing after X number of seconds. Since I’m not familiar with the command $order->get_items() or with how many records it could be possibly returning, my guess is that you could be easily spending more than a minute executing hundreds or more cURL calls.

    For things like this, verify each step along the way.

    Also, it would help if you describe exactly what is happening instead of what does not seem to be happening. That way answers can be more impactful. When you’re not sure if something is getting executed, you can always add in an echo statement to verify if the code is getting reached. Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search