Stop WordPress from removing your formatted HTML.

If you’ve ever worked with WordPress for any amount of time, you’ve probably encountered this issue. So, you’re busy adding content in the WordPress editor, which is powered by TinyMCE by the way, and at some point you switch between Visual & HTML mode.

Once you’re finished, you hit save and bam! WordPress has removed half of your nicely formatted HTML, usually messing up your design.

This is really annoying 🙁

How do we stop it?

Well, the issue lies in the TinyMCE editor, to fix we need to use a ‘hook’ in our functions.php file.


<?php
// stop wordpress removing div tags
function uncoverwp_tiny_mce_fix( $init )
{
    // html elements being stripped
    $init['extended_valid_elements'] = 'div[*]';

    // pass back to wordpress
    return $init;
}
add_filter( 'tiny_mce_before_init', 'uncoverwp_tiny_mce_fix' );

We can extend the function further to prevent WordPress messing with <br> tags and other elements too.


<?php
// stop wp removing div tags
function uncoverwp_tiny_mce_fix( $init )
{
    // html elements being stripped
    $init['extended_valid_elements'] = 'div[*], article[*]';

    // don't remove line breaks
    $init['remove_linebreaks'] = false;

    // convert newline characters to BR
    $init['convert_newlines_to_brs'] = true;

    // don't remove redundant BR
    $init['remove_redundant_brs'] = false;

    // pass back to wordpress
    return $init;
}
add_filter( 'tiny_mce_before_init', 'uncoverwp_tiny_mce_fix' );

Conclusion.

So there you have it, a simple fix and a sigh of relief when editing your content.

UncoverWP

Want us to email you occasionally with our latest courses, news & updates?

We use cookies to ensure that we give you the best possible experience on our website. If you continue to use this site we will assume that you are happy with it. OK Privacy Policy