Generate SKUs Automatically
Gives every product saved without a SKU an automatic one based on a prefix and the product ID, for example "SHOP-0142".
Opens WPIDE on
Code
add_action( 'woocommerce_admin_process_product_object', function ( $product ) {
$prefix = 'SHOP-'; // Text before the number.
$pad = 4; // Minimum number of digits.
if ( '' !== $product->get_sku( 'edit' ) || ! $product->get_id() ) {
return;
}
$sku = $prefix . str_pad( (string) $product->get_id(), $pad, '0', STR_PAD_LEFT );
if ( ! wc_get_product_id_by_sku( $sku ) ) {
try {
$product->set_sku( $sku );
} catch ( WC_Data_Exception $e ) {
// SKU already in use: leave it empty.
}
}
} );
Notes
Only fills empty SKUs when a product is saved; existing SKUs are never changed. Change $prefix and $pad.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.