Update all variations prices of a variable product in Woocommerce

前端 未结 1 1395
暖寄归人
暖寄归人 2021-01-12 23:42

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’ =>          


        
相关标签:
1条回答
  • 2021-01-13 00:20

    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

    0 讨论(0)
提交回复
热议问题