Skip to content

Instantly share code, notes, and snippets.

@nathaningram
Created July 18, 2023 20:12
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/38c3e87eb707f1f48e1ce5d2d00989ad to your computer and use it in GitHub Desktop.
Save nathaningram/38c3e87eb707f1f48e1ce5d2d00989ad to your computer and use it in GitHub Desktop.
Sanitizes HMTL from Woocommerce Product Descriptions upon post Update
// Sanitizes HMTL from Woocommerce Product Descriptions upon post Update
function sanitize_product_description( $post_id ) {
// check if post is a product
if ( 'product' === get_post_type( $post_id ) ) {
// get the post object
$product = wc_get_product( $post_id );
// sanitize the descriptions
foreach ( ['description', 'short_description'] as $desc_type ) {
// get the description
$description = $desc_type === 'description' ? $product->get_description() : $product->get_short_description();
// remove content between <h1> tags including the h1 tags themselves
$description = preg_replace('/<h1[^>]*>.*?<\/h1>/si', '', $description);
// sanitize the description
$sanitized_description = wp_strip_all_tags( stripslashes($description), true );
// update the product description
$desc_type === 'description' ? $product->set_description($sanitized_description) : $product->set_short_description($sanitized_description);
}
// save the product (disable save action to prevent infinite loop)
remove_action( 'save_post', 'sanitize_product_description' );
$product->save();
add_action( 'save_post', 'sanitize_product_description' );
}
}
add_action( 'save_post', 'sanitize_product_description' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment