First, you need to add your CSS to both your front-end and editor stylesheet.
Next, we’ll need to add a selector to the editor. I usually use the style select drop down which is normally disabled, but is perfect for this use case.
/**
* Add formatting select to WordPress WYSIWYG.
*/
function my_add_style_select_buttons( $buttons ) {
array_unshift( $buttons, 'styleselect' );
return $buttons;
}
add_filter( 'mce_buttons_2', 'my_add_style_select_buttons' );
Finally, you need to add your selector to the options in this new drop down style selector.
/**
* Customize formatting options for WordPress WYSIWYG.
*/
function my_tiny_mce_before_init_insert_formats( $init_array ) {
$style_formats = array(
array(
'block' => 'span',
'classes' => 'my-custom-style',
'title' => 'My custom style',
'wrapper' => true,
),
);
// Insert the array, JSON ENCODED, into 'style_formats'
$init_array['style_formats'] = wp_json_encode( $style_formats );
return $init_array;
}
add_filter( 'tiny_mce_before_init', 'my_tiny_mce_before_init_insert_formats' );
Now when you select text and apply “My custom style” you’re wrapping the selected text in a span
tag with the class my-custom-style
.