Strip Google Span Tags When you Cut/Paste into the WordPress Editor

You may note that when you cut/paste from Google Docs into the WordPress editor you get a bunch of span tag and inline CSS garbage. It’s awful . . . so you could paste into the plain text editor . . . but you may also find that you want to keep a bunch of the other HTML in there like links and lists and stuff.

via GIPHY

Jonathan Nicol figured this out way back in 2015 and I keep having to re-Google it or remember which theme I had it in so I’m putting it here to help me find it more easily.

You can see my slightly tweaked version below. All credit to Jonathan and thanks to him for documenting it publically.

//fix cut paste drama from https://jonathannicol.com/blog/2015/02/19/clean-pasted-text-in-wordpress/
add_filter('tiny_mce_before_init','configure_tinymce');

/**
 * Customize TinyMCE's configuration
 *
 * @param   array
 * @return  array
 */
function configure_tinymce($in) {
  $in['paste_preprocess'] = "function(plugin, args){
    var whitelist = 'p,b,strong,i,em,h2,h3,h4,h5,h6,ul,li,ol,a,href';  // Strip all HTML tags except those we have whitelisted here
    var stripped = jQuery('<div>' + args.content + '</div>');
    var els = stripped.find('*').not(whitelist);
    for (var i = els.length - 1; i >= 0; i--) {
      var e = els[i];
      jQuery(e).replaceWith(e.innerHTML);
    }
    // Strip all class and id attributes
    stripped.find('*').removeAttr('id').removeAttr('class').removeAttr('style');
    args.content = stripped.html();    // Return the clean HTML
  }";
  return $in;
}

Comments on this post

No comments.

Leave a Reply

Trackbacks and Pingbacks on this post

No trackbacks.

TrackBack URL