skip to Main Content

I have an array with product id (post_id). My goal is to loop thru this array and change all the product prices in WooCommerce products.

Here is my attempt:

foreach ($array as $product) {
    update_post_meta($product['post_id'], '_regular_price', $array['price']);
}

Array

[
  {
    "post_id": 18,
    "sku": "SNTP-UVS8P",
    "price": "59.00"
  },
  {
    "post_id": 17,
    "sku": "TD-SKU30548",
    "price": "10.00"
  },
  {
    "post_id": 16,
    "sku": "USBCV",
    "price": "29.00"
  }
]

2

Answers


  1. One way you can go about this is that you can use wc_get_product(ID) and then use set_price on the product object to set your price

    sample:

    foreach ($products as $product) {
        $wc_product = wc_get_product( $product['id'] );
        $product->set_price( $product['price'] );
        $product->save();
    }
    
    Login or Signup to reply.
  2. $array['price'] will return undefined change it to $product['price']

    foreach ($array as $product) {
      update_post_meta($product['post_id'], '_regular_price', $product['price']);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search