Michal Kurowski
Michal Kurowski

Reputation: 61

Woocommerce Change product price by ID

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"
  }
]

Upvotes: 0

Views: 994

Answers (2)

Nour Kilany
Nour Kilany

Reputation: 16

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();
}

Upvotes: 0

Fabrice Fabiyi
Fabrice Fabiyi

Reputation: 361

$array['price'] will return undefined change it to $product['price']

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

Upvotes: 1

Related Questions