GuiguiWeb
GuiguiWeb

Reputation: 53

Editing the weight of many product variations in WooCommerce

How can I edit the weight of many product variations in WooCommerce?

Upvotes: 2

Views: 1003

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253978

First you get an array of your Product Variations IDs this way:

global $wpdb;
$posts_table = $wpdb->prefix . "posts";
$variation_ids = $wpdb->get_col( "SELECT `ID` FROM $posts_table WHERE `post_status` LIKE 'publish' AND `post_type` LIKE 'product_variation'");

Then you can edit the weight for this product variations this way:

// Iterating through all product variations
foreach( $variation_ids as $variation_id ){

    // Get an instance of the product variation object
    $variation_object = wc_get_product($variation_id);

    // Get the variation weight
    $weight = $variation_object->get_weight();


    ## -- USE CONDITIONS TO SET / UPDATE WEIGHT AS YOU NEED -- ##

    // Example of conditions below
    if( $weight <= 0.2 && $weight > 0.3 ){
        $variation_object->set_weight(0.28);
    } elseif( $weight <= 0.3 && $weight > 0.5 ){
        $variation_object->set_weight(0.42);
    }

    // Example of empty weight condition
    if( empty($weight) ){
        $variation_object->set_weight(0.16);
    }

    // Example Based on variation IDs from 125 to 129
    if($variation_id >= 125 &&  $variation_id < 130 ){
        $variation_object->set_weight(0.45);
    }
}

Then you can customize the conditions to match your needs and to embed this in a function to run it once.

You can use any WC_Product and WC_Product_Variation methods on the Product Variation object $variation_object in your conditions too.

This way you will set / update all your multiple needed variations weight

Code goes in any php file of your active child theme (or theme) or also in any plugin php file.

This code is tested and works on WooCommerce 3.0+

Upvotes: 1

Related Questions