Skip to content

Instantly share code, notes, and snippets.

@nathaningram
Last active August 14, 2023 18:32
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/1b09ee1aab51fa3d5db3321649715af7 to your computer and use it in GitHub Desktop.
Save nathaningram/1b09ee1aab51fa3d5db3321649715af7 to your computer and use it in GitHub Desktop.
Remove 2+ empty lines in WooCommerce Product Descriptions
// Removes empty lines in Woo Product Long + Short Descr when 2 or more occur together
// Removes empty spaces at beginning or end of descriptions
// Fires on Post Update (works with Quick Edit)
add_action('save_post_product', 'ni_clean_up_product_content', 10, 3);
function ni_clean_up_product_content($post_ID, $post, $update) {
// Check if it's an update
if ($update) {
// Get the content and short description
$content = $post->post_content;
$short_description = get_post_meta($post_ID, '_excerpt', true);
// Replace lines with only ' ' with an empty string
$content = preg_replace("/^ \s*$/m", "", $content);
$short_description = preg_replace("/^ \s*$/m", "", $short_description);
// Remove multiple empty lines but keep a single empty line
$content = preg_replace("/(\n\s*){3,}/", "\n\n", $content);
$short_description = preg_replace("/(\n\s*){3,}/", "\n\n", $short_description);
// Remove trailing and leading empty lines
$content = trim($content);
$short_description = trim($short_description);
// Update the product content and short description without calling save_post again
remove_action('save_post_product', 'clean_up_product_content', 10);
wp_update_post(array('ID' => $post_ID, 'post_content' => $content));
update_post_meta($post_ID, '_excerpt', $short_description);
add_action('save_post_product', 'clean_up_product_content', 10, 3);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment