The Blog

WordPress TincyMCE Editor Removes Attributes

For anyone that has used WordPress, you may have realized that it uses a customized installation of the TinyMCE text editor. You may have also realized that TinyMCE is setup to manage, and clean, html as you work with it. If you switch between the “Visual” and “HTML” modes, you will see what I mean.

For example, you could add the following line of HTML code while working in HTML mode:

<pre name="code" class="html">...code...</pre>

If you switch to Visual mode, then back to HTML mode, you will see that name=”code” has been removed:

<pre class="html">...code...</pre>

I found a bunch of blogs that talked about editing an tiny_mce_gzip.php in the tiny_mce/themes/advanced/ folder (I did find out recently that the /wp-includes/js/tinymce/wp-tinymce.php file might be the one that allows a code change, but the file is large and messy). Or, using the “TinyMCE Valid Elements” WordPress plugin. But, I couldn’t find a configuration file in any of the TinyMCE directories (/wp-includes/js/tinymce/) using WordPress 3.2.1 and didn’t want to rely on the plugin to take care of this problem.

After some searching (took forever), I was able to find a way of modifying the TinyMCE configuration to allow the additional attribute. To do this, you need use the add_filter function for the tiny_mce_before_init filter hook.

To do this, you need to add some custom functions to WordPress. Typically, you can do this through your theme’s functions.php file (/wp-content/themes/mytheme/functions.php):

/**
 * Add to extended_valid_elements for TinyMCE
 *
 * @param $init assoc. array of TinyMCE options
 * @return $init the changed assoc. array
 */
function change_mce_options( $init ) {
 //code that adds additional attributes to the pre tag
 $ext = 'pre[id|name|class|style]';

 //if extended_valid_elements alreay exists, add to it
 //otherwise, set the extended_valid_elements to $ext
 if ( isset( $init['extended_valid_elements'] ) ) {
  $init['extended_valid_elements'] .= ',' . $ext;
 } else {
  $init['extended_valid_elements'] = $ext;
 }

 //important: return $init!
 return $init;
}
add_filter('tiny_mce_before_init', 'change_mce_options');

If you modify the functions.php file, you can keep the code in your theme files. That way, if you update the WordPress files, you won’t have to worry about losing any changes you may have made to any of the core files; which will probably be erased on the install.

Spread the love

No comments yet.

Leave a Comment

Remember to play nicely folks, nobody likes a troll.

You must be logged in to post a comment.