# 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".

- Type: PHP
- Runs: Run everywhere
- Category: [WooCommerce](https://wpide.com/library/category/woocommerce/)
- Requires: WooCommerce
- Tags: woocommerce, sku, products, admin
- Author: WPIDE Team
- Installs: 0
- Updated: 2026-10-28
- Page: https://wpide.com/library/woo-auto-generate-sku/

## Code

```php
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 use it

Install the free WPIDE plugin (https://wordpress.org/plugins/wpide/), find "Generate SKUs Automatically" in its snippet library and add it in one click; or create a new PHP snippet in WPIDE (or any code snippets plugin) and paste the code above. More snippets: https://wpide.com/library/
