Prevent stripping of span and p tags in TinyMCE editor

A few days back I got into trouble while working on a WordPress website. Do you want to know the problem?

Okay, I will let you know what the problem was. Actually, I was writing some text within <span> tag or <p> tags and on changing the editor to visual mode and coming back to text mode again, the tags were getting stripped. I tried to look for the fix, spent a couple of hours in debugging and fixing the problem, but nothing worked out. So, I started searching over internet forums and websites looking for a solution. Finally, I got to know about two different approaches, one for preventing the stripping of span tag in WordPress tinyMCE editor and other for preventing the stripping of p tags.

I am sharing both approaches below.

REMEMBER: Please take a complete back up of your website (both WordPress and database) before proceeding.

1. Prevent Stripping of SPAN tag using a filter:

Open your WordPress theme functions.php file and place the below line of code :

add_action( 'init', 'm_allow_contenteditable_on_html_tags' );
function m_allow_contenteditable_on_html_tags() {
    global $allowedposttags;

    $tags = array( 'span' );
    $new_attributes = array( 'contenteditable' => array() );

    foreach ( $tags as $tag ) {
        if ( isset( $allowedposttags[ $tag ] ) && is_array( $allowedposttags[ $tag ] ) )
            $allowedposttags[ $tag ] = array_merge( $allowedposttags[ $tag ], $new_attributes );
    }
}

add_filter('tiny_mce_before_init', 'm_filter_tiny_mce_before_init');
function m_filter_tiny_mce_before_init( $options ) {

    if ( ! isset( $options['extended_valid_elements'] ) ) {
        $options['extended_valid_elements'] = '';
    } else {
        $options['extended_valid_elements'] .= ',';
    }

    if ( ! isset( $options['custom_elements'] ) ) {
        $options['custom_elements'] = '';
    } else {
        $options['custom_elements'] .= ',';
    }

    $options['extended_valid_elements'] .= 'span[contenteditable|class|id|style]';
    $options['custom_elements']         .= 'span[contenteditable|class|id|style]';
    return $options;
} 

2. Prevent stripping of P tags:

Open the wp-admin/js/editor.js file and remove the below lines of code.

Code to remove:

content = content.replace( /\s*<p>/gi, '' );
content = content.replace( /\s*<\/p>\s*/gi, '\n\n' );

Minify this js file (i.e. editor.js) and replace the contents of editor-min.js with the minified code.

Example minifier: http://javascript-minifier.com/

After doing this when you will proceed with the testing, you will get success in preventing the span and p tags from getting stripped.

Please remember to have a back up first, before proceeding with the updates and do check after clearing your browsers cache in case things are not working as expected.

Please feel free to share your exprience and suggestions on this.

Good Luck 🙂

Advertisements

Aksheer Mittal has written 2 articles