| |
| <?php
|
| add_action('init', function () {
|
| if (!is_admin()) return;
|
|
|
|
|
| if (get_option('auto_sku_generated') === 'yes') return;
|
|
|
|
|
| update_option('auto_sku_generated', 'yes');
|
|
|
|
|
| $args = array(
|
| 'post_type' => 'product',
|
| 'posts_per_page' => -1,
|
| 'post_status' => 'publish',
|
| );
|
|
|
| $products = get_posts($args);
|
|
|
| foreach ($products as $product_post) {
|
| $product = wc_get_product($product_post->ID);
|
| if (!$product) continue;
|
|
|
| $name = $product->get_name();
|
| $words = preg_split('/\s+/', trim($name));
|
| $initials = '';
|
| $total_words = count($words);
|
|
|
|
|
| if ($total_words === 1) {
|
| $initials = strtoupper(mb_substr($words[0], 0, 3));
|
| } elseif ($total_words <= 4) {
|
| foreach ($words as $word) {
|
| $initials .= strtoupper(mb_substr($word, 0, 1));
|
| }
|
| } else {
|
| for ($i = 0; $i < 4; $i++) {
|
| $initials .= strtoupper(mb_substr($words[$i], 0, 1));
|
| }
|
| for ($i = 4; $i < $total_words; $i++) {
|
| $initials .= strtoupper(mb_substr($words[$i], 0, 1));
|
| }
|
| }
|
|
|
|
|
| $suffix_map = [
|
| 'pareja' => '22',
|
| 'amigos' => '22',
|
| 'trio' => '33',
|
| 'familiar' => '44',
|
| 'fiesta' => '66',
|
| ];
|
|
|
| $suffix = '1';
|
| foreach ($suffix_map as $keyword => $code) {
|
| if (stripos($name, $keyword) !== false) {
|
| $suffix = $code;
|
| break;
|
| }
|
| }
|
|
|
| $sku_base = $initials . '-' . $suffix;
|
| $sku = $sku_base;
|
|
|
|
|
| $existing_product_id = wc_get_product_id_by_sku($sku);
|
| if ($existing_product_id && $existing_product_id !== $product->get_id()) {
|
| $sku .= '-' . $product->get_id();
|
| }
|
|
|
|
|
| $product->set_sku($sku);
|
| $product->save();
|
| }
|
|
|
|
|
| });
|
|
|
| |
| |
Comments