Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update all variations prices of a variable product in Woocommerce

I need to get all variation id and update price in loop. Simple query and loop looks like:

$params = array(
  ‘posts_per_page’ => -1,
  ‘post_type’ => ‘product_variation’,
  ‘post_parent’ => $product->get_id() // tried $post-ID
);
$variations = get_posts( $params );
foreach ( $variations as $variation ) {
  $variation_ID = $variation->ID; // tried $post-ID, $product->get_id()
  $regular_price=34;
  update_post_meta( $variation_ID, ‘_regular_price’, (float)$regular_price );
  update_post_meta( $variation_ID, ‘_price’, (float)$regular_price );
}

I think not working this:

(‘post_parent’ => $product->get_id()) 

or this:

($variation_ID = $variation->ID;). 
like image 282
Katia Kovtun Avatar asked Aug 13 '17 19:08

Katia Kovtun


People also ask

How do I add bulk variations in WooCommerce?

Head to WooCommerce > Bulk Edit Products which will appear after enabling the plugin. To add variations for both the products at once, filter the product type “Variable(Parent)” from the dropdown. On the next page, all the parent variable products will be filtered and selected.


1 Answers

First in your code or should be replaced by '. Also if used $post-ID should be replaced by $post->ID

Depending on where and how you are using this code, you should try to include global $post; first to be able to use the WP_Post object $post.

Then you could try to use this customized version of your code instead:

global $post;

$regular_price = 13;

// Only for product post type
if( $post->post_type == 'product' )
    $product = wc_get_product( $post->ID ); // An instance of the WC_Product object

// Only for variable products
if( $product->is_type('variable') ){

    foreach( $product->get_available_variations() as $variation_values ){
        $variation_id = $variation_values['variation_id']; // variation id
        // Updating active price and regular price
        update_post_meta( $variation_id, '_regular_price', $regular_price );
        update_post_meta( $variation_id, '_price', $regular_price );
        wc_delete_product_transients( $variation_id ); // Clear/refresh the variation cache
    }
    // Clear/refresh the variable product cache
    wc_delete_product_transients( $post->ID );
}

This code is tested on WooCommerce version 3+ and works

like image 170
LoicTheAztec Avatar answered Oct 29 '22 15:10

LoicTheAztec