Stop WordPress removing HTML.

Stop WordPress removing 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.

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.

// stop wp removing div tags
function lovethemes_tinymce_fix( $init ) 
{
    // html elements being stripped
    $init['extended_valid_elements'] = 'div[*]';

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

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

// stop wp removing div tags
function lovethemes_tinymce_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', 'lovethemes_tinymce_fix');

Conclusion.

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

    Share This: