Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * Generate SKU programmatically
- * https://example.com/wp-admin/edit.php?post_type=product&generate_sku
- */
- function pm_generate_sku() {
- if(isset($_GET['generate_sku'])) {
- $query = new WC_Product_Query(array(
- 'limit' => -1,
- 'orderby' => 'date',
- 'order' => 'DESC',
- ));
- $products = $query->get_products();
- foreach($products as $product) {
- // Get product ID and SKU (if exists)
- $product_id = $product->get_id();
- pm_generate_single_sku($product_id);
- }
- }
- }
- add_action('admin_init', 'pm_generate_sku');
- /**
- * Add the SKU
- */
- function pm_generate_single_sku($product_id, $post, $update) {
- global $permalink_manager_uris;
- // Trigger only when product is saved for the first time + ignore other post types
- if($update || $post->post_type !== 'product') { return; }
- // Get product object
- $product = wc_get_product($product_id);
- if(empty($product)) { return; }
- // Get current SKU
- $product_sku = $product->get_sku();
- // Add SKU only to products without them
- if(!empty($product_sku)) { return; }
- // Convert the product title to the number
- $product_title_encoded = sha1($product->get_title());
- // Generate the SKU based on unique product ID + encoded product title
- $product_sku = $product_id . $product_title_encoded;
- // Keep only digits
- $product_sku = preg_replace('/\D/', '', $product_sku);
- // Trim it to 7 characters to make sure that all SKU have the same length
- $product_sku = substr($product_sku, 0, 10);
- // Save SKU
- update_post_meta($product_id, '_sku', $product_sku);
- // Generate custom permalink with SKU
- $default_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri($product_id);
- if($default_uri) {
- $permalink_manager_uris[$product_id] = $default_uri;
- update_option('permalink-manager-uris', $permalink_manager_uris);
- }
- }
- add_action('wp_insert_post', 'pm_generate_single_sku', 99, 3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement