I created a simple WordPress plugin (copied below) to add a custom button to TinyMCE that removes certain formatting, in this case span tags. I tested it out on a post whose content is as follows:
a <span style="color: red;">test</span>
But the button only works if I highlight the targeted selector only. In this case, if I highlight “test” and then click my “Remove spans” button under the “Formats” button, it works. But if I highlight “a test”, the “Remove spans” option becomes disabled and does not work.
This seems like it should be doable, since TinyMCE’s built-in “Clear formatting” button works in this situation.
My goal is to make a plugin (either by modifying the “Clear formatting” functionality or making a similar custom button) that clears certain kinds of formatting but not others. I want to remove colors but keep strong tags, for example.
Here is my full plugin code:
<?php
// Callback function to insert 'styleselect' into the $buttons array
function my_mce_buttons_2( $buttons ) {
array_unshift( $buttons, 'styleselect' );
return $buttons;
}
// Register our callback to the appropriate filter
add_filter('mce_buttons_2', 'my_mce_buttons_2');
// Callback function to filter the MCE settings
function my_mce_before_init_insert_formats( $init_array ) {
// Define the style_formats array
$style_formats = array(
// Each array child is a format with it's own settings
array(
'title' => 'Remove spans',
'selector' => 'span',
'remove' => 'all'
),
);
// Insert the array, JSON ENCODED, into 'style_formats'
$init_array['style_formats'] = json_encode( $style_formats );
return $init_array;
}
// Attach callback to 'tiny_mce_before_init'
add_filter( 'tiny_mce_before_init', 'my_mce_before_init_insert_formats' );
?>