3

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
    I appreciate your effort that you came up with something but this question, rather not-a-question is not suitable for this community. You should read this how to ask : stackoverflow.com/help/how-to-ask – Arsalan Mithani Jan 26 '17 at 14:07
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.