Remove Inline Styles From Pasted Content on Save
Cleans up formatting pasted from Word, Google Docs and web pages when a post is saved, removing inline fonts, colors and sizes, font tags, bare spans and Office classes so text follows your theme.
Opens WPIDE on
Code
// Leave administrators' content untouched.
$wpide_clean_skip_admins = false;
// Post types to clean.
$wpide_clean_post_types = array( 'post', 'page' );
add_filter( 'wp_insert_post_data', function ( $data ) use ( $wpide_clean_skip_admins, $wpide_clean_post_types ) {
if ( ! in_array( $data['post_type'], $wpide_clean_post_types, true ) || ( $wpide_clean_skip_admins && current_user_can( 'manage_options' ) ) ) {
return $data;
}
$content = wp_unslash( $data['post_content'] );
// Process only the HTML between block comments, so block attributes stay valid.
$parts = preg_split( '/(<!--.*?-->)/s', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
$depth = 0;
foreach ( $parts as $i => $part ) {
if ( 0 === strpos( $part, '<!--' ) ) {
if ( preg_match( '/^<!--\s+wp:[^\s]+\s+\{.*"style"/s', $part ) ) {
$depth++; // Styled block: keep its markup as is.
} elseif ( $depth && preg_match( '/^<!--\s+\/wp:/', $part ) ) {
$depth--;
}
continue;
}
if ( $depth ) {
continue;
}
// Keep only text alignment, which the classic editor stores as an inline style.
$part = preg_replace_callback( '/\sstyle=("|\')([^"\']*)\1/i', function ( $m ) {
return preg_match( '/text-align\s*:\s*(left|right|center|justify)/i', $m[2], $align ) ? ' style="text-align:' . strtolower( $align[1] ) . '"' : '';
}, $part );
$part = preg_replace( '/\sclass=("|\')\s*Mso[^"\']*\1/i', '', $part );
$part = preg_replace( '#</?font[^>]*>#i', '', $part );
$part = preg_replace( '#<span>(.*?)</span>#is', '$1', $part );
$parts[ $i ] = $part;
}
$data['post_content'] = wp_slash( implode( '', $parts ) );
return $data;
}, 20 );
Notes
Text alignment and blocks styled through their own settings are kept; administrators can opt out with $wpide_clean_skip_admins.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.