Created
August 30, 2023 16:27
-
-
Save nathaningram/2874a5695e0a3b3e43767a9aa63716dc to your computer and use it in GitHub Desktop.
Append WooCommerce Product SKU to Short Description (including multiple variations)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ADD SKUS | |
// Runs on update - use Quick Edit | |
function ni_append_sku_to_short_description($post_id) { | |
if ('product' !== get_post_type($post_id)) { | |
return; | |
} | |
$product = wc_get_product($post_id); | |
if (!$product) { | |
return; | |
} | |
$short_desc = $product->get_short_description(); | |
// List to hold all SKUs | |
$skus = []; | |
// Check if the product is variable | |
if ($product->is_type('variable')) { | |
$variations = $product->get_available_variations(); | |
foreach ($variations as $variation) { | |
if (isset($variation['sku']) && $variation['sku']) { | |
$skus[] = $variation['sku']; | |
} | |
} | |
} else { | |
$sku = $product->get_sku(); | |
if ($sku) { | |
$skus[] = $sku; | |
} | |
} | |
// If there are no SKUs to append, return | |
if (empty($skus)) { | |
return; | |
} | |
// Combine SKUs and check if they're already appended to the short description | |
$combined_sku_string = "SKU: " . implode(', ', $skus); | |
if (strpos($short_desc, $combined_sku_string) !== false) { | |
return; | |
} | |
$updated_desc = $short_desc . "<p>" . $combined_sku_string . "</p>"; | |
// Bypass save_post action to prevent infinite loop | |
remove_action('save_post', 'append_sku_to_short_description'); | |
wp_update_post([ | |
'ID' => $post_id, | |
'post_excerpt' => $updated_desc, // Short description is stored as post_excerpt in WP | |
]); | |
// Re-add the action | |
add_action('save_post', 'append_sku_to_short_description'); | |
} | |
add_action('save_post', 'ni_append_sku_to_short_description'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment