Auto Generating a WooCommerce SKU Stock Code

Here is a little bit of framework code that will automatically generate an SKU code in WooCommerce.
It takes the selected product category and post ID to generate a unique stock code for the product being added.

// auto generates a stock code
add_action( 'save_post', 'save_woocommerce_auto_sku' );
function save_woocommerce_auto_sku( $post_id ) {
		if ($_REQUEST['tax_input']) {
			$term = get_term_by('id',$_REQUEST['tax_input']['product_cat'][1],'product_cat');
			if ($term) {
				$acronym = "";
				$name = explode(' ', (string)$term->name);
				foreach ($name as $w) {
					$acronym .= $w[0];
				$SKU = strtoupper($acronym) . str_pad($post_id, 4);
			update_post_meta( $post_id, '_sku', $SKU);

Author: Kieran Barnes

Kieran is a PHP developer with 15 years commercial experience. Specialist in WordPress, CakePHP, CubeCart and all things PHP.

3 thoughts on “Auto Generating a WooCommerce SKU Stock Code”

  1. I would like to try your sku generating code to see if it works. Assuming it does, can’t imagine why Woocommerce doesn’t have something similar as an option to autogenerate sku’s. However, I’m not clear as to what file this code should be placed in. Rather than experiment, can you indicate what file that is? Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *