The following WordPress PHP function removes the class attributes from HTML elements in post content when saved.
It will only change class attributes inside fully formed HTML elements.
This may be useful if you are transferring content from another webpage, and do not want the HTML class attributes.
For example:
Before:
<div class="container"> <h2 class="title">My Title</h2> <p class="content">Lorem ipsum dolor sit amet</p> <a href="\" class="button">Click Here</a> <pre><p class="my_class">Example</p></pre> </div>
After:
<div> <h2>My Title</h2> <p>Lorem ipsum dolor sit amet</p> <a href="\">Click Here</a> <pre><p class="my_class">Example</p></pre> </div>
WordPress PHP function
add_action('save_post', 'itsg_remove_classes_from_post_content');
function itsg_remove_classes_from_post_content( $post_id ) {
// Only run this function for accepted post types
$accepted_post_types = array('post');
$post_type = get_post_type($post_id);
if (!in_array($post_type, $accepted_post_types)) {
return;
}
// Get the post content
$post_content = get_post_field('post_content', $post_id);
// remove classes from HTML elements
$post_content = preg_replace_callback('/<[^<>]*\sclass=[\'"`][^\'"`]*[\'"`][^<>]*>/i', function($match) {
return preg_replace('/\sclass=[\'"`][^\'"`]*[\'"`]/i', '', $match[0]);
}, $post_content);
// Temporarily remove the action to avoid infinite loop
remove_action('save_post', 'itsg_remove_classes_from_post_content');
global $wpdb;
$table_name = $wpdb->prefix . 'posts';
$data = array('post_content' => $post_content);
$where = array('ID' => $post_id);
$wpdb->update($table_name, $data, $where);
// Add the action back
add_action('save_post', 'itsg_remove_classes_from_post_content');
}
How does the function work?
The function is triggered during the ‘save_post’ action hook, which is called when a post is saved.
The function:
- checks whether the post type is one of the accepted post types (
post). If the post type is not one of these, the function exits. - gets the post content using the
get_post_fieldfunction. - uses a regular expression with
preg_replace_callbackto remove anyclassattributes from HTML elements in the post content. The regular expression matches any HTML element that contains aclassattribute, and the callback function replaces the matched string with a modified string that has theclassattribute removed. - temporarily removes the
save_postaction to avoid an infinite loop. - uses the
wpdb->updatefunction to update the post content in the database. - adds the
save_postaction back.
How to use the function?
To use the function:
- Copy the provided code to your theme’s
functions.phpfile or a custom plugin file. - If you want to target other post types, update the
$accepted_post_typesarray accordingly. For example:
$accepted_post_types = array( 'post', 'page', 'custom_post_type' );
- Save your changes and log in to your WordPress admin panel. The function will run automatically when posts are saved.