Lhen
Lhen

Reputation: 181

wc_update_order_item not saving correctly

I'm trying to update the Item Name in the wp_woocommerce_order_items table and found the function wc_update_order_item to do the trick.

I want it to change to a randomly picked product. They main thing here is I already know the order_item_id that I want to change.

Here's my code:

    $order_item_id = array(1,2,3);
    $num = 3;
    $ctr = 0;

    $products = new WP_Query( array(
       'post_type'      => 'product',
       'post_status'    => 'publish',
       'posts_per_page' => $num,
       'orderby'        => 'rand',
    ));

    if ( $products->have_posts() ): while ( $products->have_posts() ): $products->the_post();

        wc_update_order_item($order_item_id[$ctr], array('order_item_name' => $products->post->post_title));

        $ctr++;

    endwhile; wp_reset_postdata(); endif;

The wc_update_order_item() is where it is supposed to update the order item name. It does update the order_item_name but not with the current $products->post->post_title value. It updates with with a random product title.

How do I know the title being saved is different from the current post_title inside the loop? If I echo $products->post->post_title inside the loop, it displays the current product name, as it should, but the updated order_item_name has a different value.

Upvotes: 0

Views: 815

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253901

Try the following that will get the related product IDs corresponding to the Order items, to exclude them from the WP_Query, avoiding having the same product names:

$order_item_ids = array(1,2,3);
$num = 3;
$ctr = 0;

$exluded_ids = array();

// Loop through the Order items Ids
foreach ( $order_item_ids as $item_id ) {
    // Get the order ID from the order Item ID
    $order_id = wc_get_order_id_by_order_item_id( $item_id );

    // Get the WC_Order object instance
    $order = wc_get_order( $order_id );

    // Get the WC_Order_Item_Product object instance
    $item = $order->get_item( $item_id );

    // Products IDs to be excluded from the WP_Query (array)
    $exluded_ids[] = $item->get_product_id();
}

$products = new WP_Query( array(
   'post_type'      => 'product',
   'post_status'    => 'publish',
   'posts_per_page' => $num,
   'orderby'        => 'rand',
   'post__not_in'   => $exluded_ids,
));

if ( $products->have_posts() ): 
    while ( $products->have_posts() ): $products->the_post();
        wc_update_order_item($order_item_id[$ctr], array('order_item_name' => $products->post->post_title));
        $ctr++;

    endwhile; 
    wp_reset_postdata(); 
endif;

It should work.


Now as we don't know how you get the $order_item_id array, it's not possible to know what really happen. It should be better to explain what you are trying to do from the start.

Upvotes: 1

Related Questions