Set WooCommerce product SKU programmatically

/**
 * Sets product SKU.
 *
 * @see https://wpcodebook.com/woocommerce-set-product-sku-programmatically/
 */
add_filter( 'woocommerce_product_get_sku', function ( $sku, $product ) {
	return $product->get_id();
}, 10, 2 );

The example sets WooCommerce product SKU to product ID. Another example adds up to six leading zeros and includes a custom prefix in SKU:

return sprintf( 'MY_PREFIX-%06s', $product->get_id() );

Variations

/**
 * Sets variation SKU.
 *
 * @see https://wpcodebook.com/woocommerce-set-product-sku-programmatically/
 */
add_filter( 'woocommerce_product_variation_get_sku', function ( $sku, $variation ) {
	return $variation->get_parent_id() . '-' . $variation->get_id();
}, 10, 2 );

Leave a Comment