<?php // Include WordPress bootstrap file require_once('wp-load.php'); // Get global database object global $wpdb; // Function to generate SKU for variations function generate_variation_sku($parent_sku, $attributes) { $sku = $parent_sku; foreach ($attributes as $attribute) { $sku .= '-' . strtoupper($attribute); } return $sku; } // Get all published parent products $parent_products = $wpdb->get_results(" SELECT ID, post_title FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' "); if ($parent_products) { $count = 1; // SKU counter foreach ($parent_products as $parent_product) { $parent_id = $parent_product->ID; // Get parent SKU $parent_sku = get_post_meta($parent_id, '_sku', true); // If parent SKU is empty or not set, assign a new SKU if (empty($parent_sku)) { $parent_sku = sprintf('%03d', $count); // Format SKU as 001, 002, etc. update_post_meta($parent_id, '_sku', $parent_sku); // Get variations for the parent product $variations = get_posts(array( 'post_type' => 'product_variation', 'post_status' => 'publish', 'post_parent' => $parent_id, 'fields' => 'ids' )); if ($variations) { foreach ($variations as $variation_id) { // Get attributes for the variation $variation_attributes = wc_get_product_variation_attributes($variation_id); // Generate SKU for the variation $variation_sku = generate_variation_sku($parent_sku, array_values($variation_attributes)); // Update SKU for the variation update_post_meta($variation_id, '_sku', $variation_sku); } } $count++; // Increment SKU counter } } echo 'SKUs assigned successfully!'; } else { echo 'No parent products found.'; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter