
Auto-Generate Product SKUs in WooCommerce Using save_post Hook
In WooCommerce, each product can be assigned a Stock Keeping Unit (SKU), which serves as a unique identifier for managing inventory, syncing with ERP systems, or tracking product variations. By default, WooCommerce requires manual input of SKUs, but for stores that don’t rely on external systems, you might want to auto-generate SKUs for convenience.
In WooCommerce, SKU values are stored in the postmeta
table with the meta key _sku
. Based on this information, we can easily implement a function to auto-generate SKUs whenever a new product is saved.
How It Works
We hook into WordPress’s save_post
action, which fires whenever a post or custom post type (like a product) is saved. In the callback function, we check whether the post type is a product
. If it is, we generate a random identifier using WordPress’s built-in wp_generate_uuid4()
function, strip out the dashes, and check whether the product already has an SKU. If not, we assign the generated code as its SKU.
Here’s the full implementation:
add_action('save_post', function ($post_id)
{
// Check if the post type is 'product'
if (get_post_type($post_id) === 'product') {
// Generate a UUID and remove dashes
$product_number = str_replace('-', '', wp_generate_uuid4());
// Check if the product already has an SKU
$sku = get_post_meta($post_id, '_sku', true);
// If no SKU exists, assign the generated one
if (empty($sku)) {
update_post_meta($post_id, '_sku', $product_number);
}
}
});
Important Notes
- SKU Uniqueness: SKU must be unique across all products in WooCommerce. Although UUID4 is extremely unlikely to produce duplicates, this script does not explicitly check for existing SKU collisions. You may want to add a validation step if needed.
- ERP or Inventory Systems: In professional e-commerce environments, SKUs are often managed by external ERP or inventory management systems. In such cases, auto-generating SKUs via code could cause sync issues or data mismatches. Avoid using this script unless you’re sure SKU management is isolated to WooCommerce.
- When to Use: This solution is best for small stores, MVPs, or stores where SKUs are only used internally and do not need to match external systems.