Skip to content

Instantly share code, notes, and snippets.

@nathaningram
Created August 30, 2023 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathaningram/2874a5695e0a3b3e43767a9aa63716dc to your computer and use it in GitHub Desktop.
Save nathaningram/2874a5695e0a3b3e43767a9aa63716dc to your computer and use it in GitHub Desktop.
Append WooCommerce Product SKU to Short Description (including multiple variations)
// 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