How to make WordPress and TinyMCE accept tags wrapping block-level elements as allowed in HTML5?

[*]

A few years down the track, but hopefully someone else will find this solution useful…

Although my issues trying to get this sort of thing to work in WordPress were slightly different, hopefully this solution will work for you too.

Firstly, the issue with tags not being allowed to contain multiple block level elements was solved by adding the following code from this article to my functions.php file…

function allow_all_tinymce_elements_attributes( $init ) {

    // Allow all elements and all attributes
    $ext="*[*]";

    // Add to extended_valid_elements if it already exists
    if ( isset( $init['extended_valid_elements'] ) ) {
        $init['extended_valid_elements'] .= ',' . $ext;
    } else {
        $init['extended_valid_elements'] = $ext;
    }

    // return value
    return $init;
}

add_filter('tiny_mce_before_init', 'allow_all_tinymce_elements_attributes');

… and then making sure that my tag is given a name. This allowed me to enter and successfully save the following in the Text tab…

Some text.
<div>
<a href="https://somewhere.com/product/this_prod/" name="link">
<h2>THIS PRODUCT</h2>
Cost efficient Blablabla</a>
</div>

For the second issue, of code being stripped when switching from the “text” to the “visual” tab, I simply turned off the visual tab for a particular post type. I adapted the initial code found in this article, which originally targeted a post ID instead of a post type. I added this code to my functions.php file…

add_filter('user_can_richedit', 'disable_wyswyg_to_preserve_my_markup');
function disable_wyswyg_to_preserve_my_markup( $default ){
  if( get_post_type() == 'product') return false;
  return $default;
}

If this doesn’t work for a custom post type, you could try adding the following line above the previous code…

add_theme_support( 'post-formats', 'my_custom_post_type' );

Or, to solve this second issue, you could alternatively try a plugin such as this one.

[*]

Leave a Comment