Created
July 18, 2023 20:12
-
-
Save nathaningram/38c3e87eb707f1f48e1ce5d2d00989ad to your computer and use it in GitHub Desktop.
Sanitizes HMTL from Woocommerce Product Descriptions upon post Update
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
// 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