How to add your own button to TinyMCE editor

How to add your own button to TinyMCE editor

Let’s expand on this topic a bit by slightly improving the code for creating a custom button in the WordPress text editor. It’s not a major change, but this code turned out to be useful in one of my projects. I hope it will be helpful for you too, as there's not much information in Russian about the TinyMCE WYSIWYG editor — and it’s quite an interesting topic.

Today, instead of inserting text at the cursor position, we’ll be “wrapping” the selected text with a predefined tag. The tag will be <span> with a predefined class important. It will look something like this:

Text before span <span class=«important»>text inside span</span> text after span.

Nothing complicated. But for example, the SyntaxHighlighter plugin is missing a button like this. Though ideally, that would require a popup dialog allowing users to paste code and choose the language (php, js, html, etc.). By the way! That could be a great idea for the future — and a chance to deepen your understanding of the TinyMCE API.

I won’t repeat the code for adding hooks to include the plugin file or for registering the editor button, since you can find it in the previous article. Let’s focus now on the JavaScript code for our TinyMCE extension:

(function(){
	tinymce.PluginManager.add('mxs__mce_plugin', function( editor, url ) {
		editor.addButton('mxs__mce_button', {
			text: 'select',
			image: false,
			onclick: function() {
				editor.selection.setContent('<span class="important">' + editor.selection.getContent() + '</span>');
			}
		});
	});
})();

What changed here? We updated the button label to “highlight” and replaced the onclick handler with:

editor.selection.setContent('<span class="important">' + editor.selection.getContent() + '</span>');

This uses two editor methods:

  • editor.selection.getContent() — to get the selected content
  • editor.selection.setContent() — to replace it with new content at the cursor’s location

So essentially, we’re just overwriting the selected content, wrapping it in the desired tag.

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 *