Site icon Experience Wordpress Developer Online – Design Develop and Maintenance Support

How to update/add sku to all products in Woocommerce

Now I will discuss about How to update/add sku of all products in Woocommerce. To do this I want to create some products in my woocommerce store without SKU.

Now I want to update / add sku to all product in my woocommerce store. To do this add the following line of code at the end of your theme’s functions.php file of your active child theme (or theme) and Save the file.

After that go to refresh your store front just once and you’ll notice the product’s sku has been updated/added.

Remove the code from file after your store’s sku being updated. If you don’t remove after one use, products SKU will change everytime you visit any page of your site.

add_filter( 'init', 'update_sku', 10, 1);
    function update_sku( $sku ){
         $args = array(
                'post_type' => 'product',
                'posts_per_page' => 12
                );
        $i=0;
        $loop = new WP_Query( $args );

        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();

                $random_sku = mt_rand(100000, 999999);

                update_post_meta($loop->post->ID,'_sku',$random_sku);

                $i++;
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    }
Exit mobile version