David Martin
David Martin

Reputation: 51

Update price of a WooCommerce product in PHP

I'm trying to change the prices of various products on my WooCommerce website, but I have a problem. When I run the script, if I change correctly in the database and goals, the front of the web still appears as the wrong prices, even some prices appear "Free".

The strangest thing of all is that by entering the product edition if I see the prices correctly.

I give you the code sample:

$stock          = $value['stock'];
$regular_price  = $value['rates']['2']['rate_pvp'];

update_post_meta($post_id, '_regular_price',    $regular_price);
update_post_meta($post_id, '_price',            $regular_price);

$product->set_price($regular_price);

if($stock>0){
    update_post_meta($post_id, '_stock_status', 'instock');
} else {
    update_post_meta($post_id, '_stock_status', 'outofstock');
}

update_post_meta($post_id, '_stock', $stock);

echo $post_id . ':' . $value['variation_sku'] . ':' . $stock . '.............................OK<br/>';

wc_delete_product_transients();

Upvotes: 5

Views: 16410

Answers (1)

Ali Parsa
Ali Parsa

Reputation: 131

I had same problem. i think that you should reset the query object of wordpress. Here my sample that work properly.

$args = array( 'post_type' => 'product',  'product_cat' => $key);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); 
    global $product; 
    update_post_meta($product->id, '_regular_price', (float)$value);
    update_post_meta($product->id, '_price', (float)$value);
endwhile; 
wp_reset_query();  

I hope that this is useful.

Upvotes: 9

Related Questions