How to create tinymce buttons at wordpress

To create mce buttons to your wordpress tiny editor, just follow below 2 steps.

Step-1: Add following code to your function.php file. This file found at /wp-content/themes/YOUR_THEME/function.php.

/*		CREATE TINY EDITOR BUTTONS					*/
 
// Hooks your functions into the correct filters
function my_add_mce_button() {
	// check user permissions
	if ( !current_user_can( 'edit_posts' ) && !current_user_can( 'edit_pages' ) ) {
		return;
	}
	// check if WYSIWYG is enabled
	if ( 'true' == get_user_option( 'rich_editing' ) ) {
		add_filter( 'mce_external_plugins', 'my_add_tinymce_plugin' );
		add_filter( 'mce_buttons', 'my_register_mce_button' );
	}
}
add_action('admin_head', 'my_add_mce_button');

// Declare script for new button
function my_add_tinymce_plugin( $plugin_array ) {
	$plugin_array['my_mce_button'] = get_template_directory_uri() .'/mg-mce-btns.js';
	return $plugin_array;
}

// Register new button in the editor
function my_register_mce_button( $buttons ) {
	array_push( $buttons, 'my_mce_button' );
	return $buttons;
}

 

Step-2: Create file mg-mce-btns.js, Save this file to /wp-content/themes/YOUR_THEME. Note: Save file into same directory where function.php. Copy below code and place it into mg-mce-btns.js file.

 

(function() {
	tinymce.PluginManager.add('my_mce_button', function( editor, url ) {
		editor.addButton( 'my_mce_button', {
			text: 'JQuery',
			icon: false,
			type: 'menubutton',
			menu: [
				{
					text: 'Item 1',
					menu: [
						{
							text: 'Sub Item 1',
							onclick: function() {
								editor.insertContent('This is Sub Item-1');
							}
						},
						{
							text: 'Sub Item 2',
							onclick: function() {
								editor.insertContent('This is Sub Item-2');
							}
						}
					]
				},
				{
					text: 'Item 2',
					menu: [
						{
							text: 'Sub Item 1',
							onclick: function() {
								editor.insertContent('This is Munu-2 - Sub Item-1');
							}
						},
						{
							text: 'Sub Item 2',
							onclick: function() {
								editor.insertContent('This is Munu-2 - Sub Item-2');
							}
						}
					]
				}
			]
		});
	});
})();

 

Result:

How to create drop down mce buttons at wordpress tiny editor window

Download complete source code: Source files

Advertisements

Author: maheshwaghmare

WordPress Developer since 2012

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s