In WooCommerce, the Stock Keeping Unit (SKU) is a critical identifier stored in the postmeta table under the key _sku. While many businesses use structured SKU patterns, some scenarios—like digital marketplaces or high-volume dropshipping—benefit from automatically generated, unique identifiers. By leveraging WordPress’s built-in utility functions, we can automate this process entirely.
The Automatic SKU Generator
We’ll use the save_post hook to intercept the product saving process. If a new product is created and it doesn’t already have an SKU, our function will generate a unique ID using the wp_generate_uuid4() function, strip the hyphens, and save it to the database.
add_action('save_post', function ($post_id) {
// Only target the 'product' post type
if (get_post_type($post_id) === 'product') {
// Check if an SKU already exists
$sku = get_post_meta($post_id, '_sku', true);
if (empty($sku)) {
// Generate a random 32-character hex string (UUID v4 sans hyphens)
$random_sku = str_replace('-', '', wp_generate_uuid4());
// Save the new SKU
update_post_meta($post_id, '_sku', $random_sku);
}
}
});
Best Practices for SKU Management
While random SKUs are convenient, keep these points in mind:
- Uniqueness:
wp_generate_uuid4()provides extremely high collision resistance, making it safe for nearly all store sizes. - ERP/Inventory Sync: If you use external inventory management software, ensure your automated SKUs are compatible with their naming conventions.
- Human Readability: Random strings are harder for warehouse staff to identify visually than structured codes (e.g.,
TSHIRT-RED-L). Only use random SKUs if visual identification isn’t part of your workflow.
Automating your SKU generation removes one more manual step from your product listing workflow, allowing you to scale your WooCommerce store more efficiently.
