Snippet: Use classes instead of inline styles for text alignment

WordPress’ TinyMCE (WYSIWYG) editor is adding inline stlyes to the markup when you change the text alignment. This behaviour is hard coded in wp-includes/class-wp-editor.php.

Can the inline styles be changed to classes instead?

2 Answers
2

Note This answer was originally included in @bitstarr’s question above and was included as a separate answer here to comply with WPSE’s Q&A model.


Maybe someone else will have this issue and so i will share my solution here with you folks.

function make_mce_awesome( $init ) {
    /*
        There are easier things than make 'left/center/right align text' to use classes instead of inline styles
     */

    // decode
    $formats = preg_replace( '/(\w+)\s{0,1}:/', '"\1":', str_replace(array("\r\n", "\r", "\n", "\t"), "", $init['formats'] ));
    $formats = json_decode( $formats, true );

    // set correct values
    $formats['alignleft'][0]['classes'] = 'text--left';
    $formats['aligncenter'][0]['classes'] = 'text--center';
    $formats['alignright'][0]['classes'] = 'text--right';

    // remove inline styles
    unset( $formats['alignleft'][0]['styles'] );
    unset( $formats['aligncenter'][0]['styles'] );
    unset( $formats['alignright'][0]['styles'] );

    // encode and replace
    $init['formats'] = json_encode( $formats );

    return $init;
}
add_filter( 'tiny_mce_before_init', 'mkae_mce_awesome' );

First the settings have to be encoded to make them easy usable in PHP. Then we i add the class names (text--XXX) and remove the parts that cause the inline styling. At the end the array will be converted back.

Bonus: You can make the editor even more awesome by adding this line.

    $init['block_formats'] = 'Paragraph=p;Heading 2=h2;Heading 3=h3;Heading 4=h4';

This will prevent users from using <h1> headlines – the SEO nightmare…

I hope this will be useful for somebody. Improvements are welcome!

Also see https://wordpress.stackexchange.com/a/141539

Leave a Comment