Updating line items through code in WooCommerce

I’m trying to make an interface where I can edit some of the metadata attached to a lineitem. I’ve tried using update_post_meta() on the line item itself, however that returns bool(false). How can I update the line item meta data manually?

Thanks!

Related posts

Leave a Reply

1 comment

  1. so I managed to figure it out. I wrote a small function that’s below. So, all you need to do is load up the order using the API, parse through each line item and you can call wc_update_order_item_meta. The only thing is, you need to know the variation ID of the item being sold if you only want to update a specific item.

    function update_order_item_meta($orderID, $variationID, $metaID, $metaValue) {
    $order = returnWC_API()->get_order($orderID)->{'order'};
    if(!$order) {
        return false;
    }
    if($variationID == "all") {
        foreach ($order->{'line_items'} as $line_item) {
            if(!wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue)) {
                return false;
            }
        }
        return true;
    }
    
    foreach ($order->{'line_items'} as $line_item) {
        if($line_item->{'product_id'} == $variationID) {
            return wc_update_order_item_meta($line_item->{'id'}, $metaID, $metaValue);
        }
    }
    

    }