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
}
}
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.