'Save order meta when using the "woocommerce_new_order" hook

I need to trace if a product is bought from a user coming from a specific site, that's why I need to set a meta for the order.

Let's focus on this piece of my code:

add_action( 'woocommerce_new_order', 'add_affilate_meta', 10, 1);

function add_affilate_meta( $order_id ){
   $targetProd = 3115;
   
   // check if product is present
   $order = wc_get_order( $order_id ); 

   $affiliationProduct = false;    
   foreach ($order->get_items() as $item_key => $item ):
     $product_id = $item->get_product_id();

      if($product_id == $targetProd):
        $affiliationProduct = true;
        break;
      endif;
    endforeach;

    // this is just for debug
    update_post_meta( $order_id, 'test_affiliate', $product_id );

    ... some other stuff ...
}

$affiliationProduct and, consequently, test_affiliate meta are always false/empty. Why? I'm sure, of course, that the article is present in the order. It seems like the order is not "ready" when I try to analyze it's content.

I cannot find any other way to debug the code, because I cannot var_dump() nothing without causing JSON errors.

Any help will be appreciated.



Solution 1:[1]

You can indeed use the woocommerce_new_order hook, but what is missing in your code is $order->save();

So you get:

function action_woocommerce_new_order( $order_id ) {
    // Get the WC_Order Object
    $order = wc_get_order( $order_id );

    // Setting
    $target_prod = 30;

    // Initialize
    $affiliation_product = false;
    $product_id = 0;
   
    // Loop trough
    foreach ( $order->get_items() as $item_key => $item ) {
        // Get 
        $product_id = $item->get_product_id();

        // Compare
        if ( $product_id == $target_prod ) {
            $affiliation_product = true;
            break;
        }
    }
    
    // Update meta data         
    $order->update_meta_data( 'test_affiliate', $product_id );
    
    // Save
    $order->save();
        
    // When true
    if ( $affiliation_product ) {
        // Do something
    }
}
add_action( 'woocommerce_new_order', 'action_woocommerce_new_order', 10, 1 );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 7uc1f3r