How to Add a Custom Button to the WordPress Editor

How to Add a Custom Button to the WordPress Editor

In this article, we'll look at a simple example of how to create a custom button for the WordPress text editor.

For those who don’t know, WordPress uses the TinyMCE web editor script. It’s a free script, and judging by the fact that it’s used in this CMS (it was also used in Joomla in the past — not sure about now), it clearly has some advantages over other editors.

As an example, we’ll create a button that, when clicked, inserts the stress mark character code into the editor text.

To create your own button, we’ll need the functions.php file of our theme. Although we could create a separate plugin for this, since our code is relatively small, we’ll use the functions file instead.

Open the file and add the following code:

add_filter('mce_external_plugins', function($plugin_array){
	
	$plugin_array['mxs__mce_plugin'] = get_template_directory_uri().'/javascript/mxs__mce_plugin.js';
	
	return $plugin_array;
});

Using the mce_external_plugins filter, we add the URL of our plugin's JS file to the list of external plugins by setting it as a value in the $plugin_array array under the specified key.

Next, we add our button to the editor using another hook:

add_filter('mce_buttons', function($buttons){
	$buttons[] = 'mxs__mce_button';

	return $buttons;
});

And the most important part — the code of our plugin (file mxs__mce_plugin.js):

(function(){
	tinymce.PluginManager.add('mxs__mce_plugin', function( editor, url ) {
		editor.addButton('mxs__mce_button', {
			text: 'ударение',
			image: false,
			onclick: function() {
				editor.insertContent('́');
			}
		});
	});
})();

The example above shows a simple use of TinyMCE. When the button labeled “ударение” (“stress mark”) is clicked (in our case it’s a text button), the onclick event is triggered, and the stress mark character code ́ is inserted at the cursor position.

As you can see, it’s pretty straightforward. With good knowledge of the TinyMCE API, you can build multi-window applications with rich functionality.

Posts on similar topics

Are you having problems with your WordPress site? Do you need additional functionality? A custom plugin or a new page?
Then write to me via the feedback form, and I will try to help you.

Write a comment

Your email address will not be published. Required fields are marked *