Check the SKU in WooCommerce before saving a new product

327 Views Asked by At

I hope you can help me out.

I need to check the SKU before saving a new product

And I also want to avoid errors due to duplicated SKU value. The SKU should just be change so it is unique.

I have tried a lot of combinations and different hooks – and nothing happens, the product just saves whether or not the SKU is set.

// Disable default duplicte sku check
add_filter( 'wc_product_has_unique_sku', '__return_false' ); 

//Check SKU
add_action( 'woocommerce_before_product_object_save', 'set_sku', 50, 2 );
function set_sku( $product_id, $product ) {
    function generateRandomString($length = 10) {
        return substr(str_shuffle(str_repeat($x='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length/strlen($x)) )),1,$length);
    }
    $currentSku = $product->get_sku();
    if( empty( $currentSku ) ) { //If SKU field is empty then use slug for SKU
        $product->set_sku($product->get_slug());
    }else if( !wc_product_has_unique_sku($product_id, $currentSku ) )  {
        $product->set_sku($currentSku.'-'.$generateRandomString()); //SKU duplicated - add random string to end
    }
}
1

There are 1 best solutions below

1
On

Why don't you just use the 'pre_post_update' hook? The hook 'woocommerce_before_product_object_save' doesn't work, it was probably removed.

   add_action( 'pre_post_update', 'set_sku', 50, 2 );
   function set_sku( $product_id, $product_data ) {
     // Only run this code for products
     if ($product_data['post_type'] !== 'product') {
       return;
     } 
    $product = wc_get_product($product_id);
    //... your sku related code ...