In WordPress v4+, I want to remove all hidden formatting when users paste content into TinyMCE visual editor.
The Paste as Text button works when users insert text from Microsoft Word but doesn’t do its job with other applications like Pages for OSX.
You can use the following to filter away all formatting for Word (thanks Till Kruss):
class PasteAsPlainText {
function __construct() {
add_action( 'admin_init', array( $this, 'init' ) );
}
function init() {
add_filter( 'tiny_mce_before_init', array( $this, 'forcePasteAsPlainText' ) );
add_filter( 'teeny_mce_before_init', array( $this, 'forcePasteAsPlainText' ) );
add_filter( 'teeny_mce_plugins', array( $this, 'loadPasteInTeeny' ) );
add_filter( 'mce_buttons_2', array( $this, 'removePasteAsPlainTextButton' ) );
}
function forcePasteAsPlainText( $mceInit ) {
global $tinymce_version;
if ( $tinymce_version[0] < 4 ) {
$mceInit[ 'paste_text_sticky' ] = true;
$mceInit[ 'paste_text_sticky_default' ] = true;
} else {
$mceInit[ 'paste_as_text' ] = true;
}
return $mceInit;
}
function loadPasteInTeeny( $plugins ) {
return array_merge( $plugins, (array) 'paste' );
}
function removePasteAsPlainTextButton( $buttons ) {
if( ( $key = array_search( 'pastetext', $buttons ) ) !== false ) {
unset( $buttons[ $key ] );
}
return $buttons;
}
}
new PasteAsPlainText();
And then you can hide the Paste as Text button (to disallow users from unticking it) by selecting which buttons you want to show:
function formatTinyMCE( $in ) {
$in['toolbar1'] = 'bold,custom_em,blockquote,aligncenter,link,unlink,spellchecker,undo,removeformat';
return $in;
}
add_filter( 'tiny_mce_before_init', 'formatTinyMCE' );
Now that we have got Word out of the way (finally), how do we completely strip all hidden formatting pasted into TinyMCE?
UPDATE: One approach could be to find an init option like paste_word_valid_elements and have an empty list of valid tags.