Automatically set SKU on product update in WooCommerce

/**
 * Sets SKU (for products with no SKU) on product or variation update.
 *
 * @see https://wpcodebook.com/woocommerce-automatically-set-sku-product-update/
 * @see https://github.com/woocommerce/woocommerce/blob/8.1.1/plugins/woocommerce/includes/abstracts/abstract-wc-product.php#L1451
 */
add_action( 'woocommerce_after_product_object_save', function ( $product ) {
	if ( '' === $product->get_sku( 'edit' ) ) {
		$product->set_sku( sprintf( 'WPCB-%08s', $product->get_id() ) );
		$product->save();
	}
} );

Leave a Comment