Search code examples
phpwordpresswoocommerceproductsku

Woocommerce SKU Generator: Generate a sku for all variations same as parent sku


i need a simply function that allow me to add or replace empty sku code for variation in my published product with parent sku of product.

is there a way to obtain this work?


Solution

  • Updated: To replace empty SKU code for variation in your published product with the parent SKU (the variable product SKU), try this function that will only work for admin user role.

    Do a database backup before runing this

    To run this function, browse your shop page:

    • It will update 2500 empty variations SKU each time.
    • A message will display the count of updated variations.
    • Each time you will need to reload the page to process 2000 variations SKUs.,

    When all variations SKUs will be updated, a message let you know that the job is done.

    The code:

    add_action('woocommerce_before_main_content', 'update_variations_sku', 100 );
    function update_variations_sku(){
        global $wpdb;
        $results = $results2 = array();
        $limit = 2500; // Number of variations to process
    
        // The SQL query (get the variations with empty sku and their parent product ID)
        $query = $wpdb->get_results( "
            SELECT p.ID, p.post_parent
            FROM {$wpdb->prefix}posts as p
            INNER JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
            WHERE p.post_type LIKE 'product_variation'
            AND p.post_status LIKE 'publish'
            AND pm.meta_key LIKE '_sku'
            LIMIT $limit
        " );
    
        if( count($query) == 0 ){
            echo "<p><pre>The job is finished, you can remove the code</pre></p>";
            return; // exit
        }
    
        // Loop through variation Ids and get the parent variable product ID
        foreach( $query as $value )
            $results[$value->post_parent][] = $value->ID;
    
        // Loop through variation Ids and set the parent sku in related empty variations skus
        foreach($results as $parent_id => $variation_ids){
            $parent_sku = get_post_meta( $parent_id, '_sku', true );
            $count = 0;
            foreach($variation_ids as $variation_id){
                $count++;
                update_post_meta( $variation_id, '_sku', $parent_sku.'-'.$count );
    
            }
        }
        if( count($query) < $limit ){
            echo "<p><pre>The job is finished, you can remove the code <br>$count variations SKUs have been updated</pre></p>";
        } else {
            echo "<p><pre>$count variations SKUs have been updated (continue reloading the page again)</pre></p>";
        }
    }
    

    Code goes in function.php file of your active child theme (or theme).

    Tested and works.