Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Customizing TinyMCE's Formats (style_select) dropdown in rich text widgets in WordPress 4.8x
<?php
// PHP goes in functions.php or similar
// Callback function to filter the MCE settings
function my_mce_style_options( $init_array ) {
// Define the style_formats array
$style_formats = my_mce_styleselect_options();
// Insert the array, JSON ENCODED, into 'style_formats'
$init_array['style_formats'] = json_encode( $style_formats );
$init_array['preview_styles'] = false;
return $init_array;
}
add_filter( 'tiny_mce_before_init', 'my_mce_style_options' );
/*
Define the styleselect ("Formats") dropdown menu options. To be used as PHP in my_mce_style_options() and as JSON in my_rich_text_widget_buttons_enqueue()
/**/
function my_mce_styleselect_options() {
return array(
// Each array child is a format with its own settings
array(
'title' => __( 'Button Link' ),
'selector' => 'a',
'classes' => 'button'
),
array(
'title' => __( 'Uppercase' ),
'selector' => 'h1, h2, h3, h4, h5, h6, p, span, li, dt',
'inline' => 'span',
'classes' => 'uppercase'
),
array(
'title' => __( 'Red' ),
'selector' => 'h1, h2, h3, h4, h5, h6, p, blockquote, span, li, dt',
'inline' => 'span',
'classes' => 'red'
)
);
}
// Declare script for rich text widget buttons
function my_rich_text_widget_buttons_enqueue( $hook ) {
if ( 'widgets.php' !== $hook )
return;
wp_enqueue_script( 'my_rich_text_widget_buttons', get_stylesheet_directory_uri() . '/js/rich-text-widget-buttons.js', array( 'jquery' ), '1.0', true );
wp_localize_script(
'my_rich_text_widget_buttons',
'TinyMCE_formats',
my_mce_styleselect_options()
);
}
add_action( 'admin_enqueue_scripts', 'my_rich_text_widget_buttons_enqueue' );
?>
// JS file: rich-text-widget-buttons.js
jQuery( document ).on( 'tinymce-editor-setup', function( event, editor ) {
if ( editor.settings.toolbar1 && -1 === editor.settings.toolbar1.indexOf( 'styleselect' ) ) {
editor.settings.toolbar1 += ',styleselect';
}
});
jQuery( document ).on( 'wp-before-tinymce-init', function( event, settings ) {
settings.style_formats_merge = false;
settings.style_formats = TinyMCE_formats;
settings.preview_styles = false;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.