Woocommerce update sku of all products? filter?

2019-09-05 16:55发布

I'd like to set the SKU to the ID of the product.. but cannot find the right filter to use?

Is there a filter that sends the product SKU?

add_filter( 'woocommerce_get_sku', 'update_sku', 10, 1);

function update_sku( $sku ){

//set $newsku as product id


    return $newsku;
}

How do i accomplish this? I have 1000s of products without a SKU. I've tried a plugin called SKU generator but that doesn't work. Any help appreciated.

1条回答
Ridiculous、
2楼-- · 2019-09-05 17:26

You can do it by adding following code to your functions.php file and after adding go to you site example.com for only once.

After that remove below code from the functions.php.

    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();
    }

NOTE : If you don't remove after one use, products SKU will change everytime you visit any page of your site.

查看更多
登录 后发表回答