Advertisement
mbis

Generate SKU programmatically

Oct 28th, 2019
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.91 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Generate SKU programmatically
  4.  * https://example.com/wp-admin/edit.php?post_type=product&generate_sku
  5.  */
  6. function pm_generate_sku() {
  7.     if(isset($_GET['generate_sku'])) {
  8.         $query = new WC_Product_Query(array(
  9.         'limit' => -1,
  10.         'orderby' => 'date',
  11.         'order' => 'DESC',
  12.         ));
  13.  
  14.         $products = $query->get_products();
  15.  
  16.         foreach($products as $product) {
  17.             // Get product ID and SKU (if exists)
  18.             $product_id = $product->get_id();
  19.  
  20.             pm_generate_single_sku($product_id);
  21.         }
  22.     }
  23. }
  24. add_action('admin_init', 'pm_generate_sku');
  25.  
  26. /**
  27.  * Add the SKU
  28.  */
  29. function pm_generate_single_sku($product_id, $post, $update) {
  30.     global $permalink_manager_uris;
  31.  
  32.     // Trigger only when product is saved for the first time + ignore other post types
  33.     if($update || $post->post_type !== 'product') { return; }
  34.  
  35.     // Get product object
  36.     $product = wc_get_product($product_id);
  37.  
  38.     if(empty($product)) { return; }
  39.  
  40.     // Get current SKU
  41.     $product_sku = $product->get_sku();
  42.  
  43.     // Add SKU only to products without them
  44.     if(!empty($product_sku)) { return; }
  45.  
  46.     // Convert the product title to the number
  47.     $product_title_encoded = sha1($product->get_title());
  48.  
  49.     // Generate the SKU based on unique product ID + encoded product title
  50.     $product_sku = $product_id . $product_title_encoded;
  51.  
  52.     // Keep only digits
  53.     $product_sku = preg_replace('/\D/', '', $product_sku);
  54.  
  55.     // Trim it to 7 characters to make sure that all SKU have the same length
  56.     $product_sku = substr($product_sku, 0, 10);
  57.  
  58.     // Save SKU
  59.     update_post_meta($product_id, '_sku', $product_sku);
  60.  
  61.     // Generate custom permalink with SKU
  62.     $default_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri($product_id);
  63.  
  64.     if($default_uri) {
  65.         $permalink_manager_uris[$product_id] = $default_uri;
  66.         update_option('permalink-manager-uris', $permalink_manager_uris);
  67.     }
  68. }
  69. add_action('wp_insert_post', 'pm_generate_single_sku', 99, 3);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement