Using The TinyMCE Editor In WordPress [Guide]

Although they may not know its name, everyone who uses WordPress is familiar with the TinyMCE editor. It’s the editor you use when you create or edit your content – the one with the buttons for creating bold text, headings, text alignment and so on is. That’s what we’ll be taking a look at in this post, and I’m going to show you how you can add functionality and how you can use it in your plugins.

The editor is built on a platform-independent Javascript system called TinyMCE which is used in a number of projects on the Web. It has a great API which WordPress allows you to tap into to create your own buttons and to add it to other locations within WordPress.

Adding Available Buttons

WordPress uses some options available in TinyMCE to disable particular buttons – such as superscript, subscript and horizontal rules – in order to clean up the interface. They can be added back without too much fuss.

The first step is to create a plugin. Take a look at the WordPress codex on how to do that. In a nutshell, you can get by with creating a folder named ‘my-mce-plugin’ in the wp-content/plugins folder. Create a file with the same name, with a PHP extension: my-mce-plugin.php.

Inside that file paste the following:

<?php
/**
    *Plugin Name: My TinyMCE plugin
    *Description: A plugin for adding custom functionality to the WordPress TinyMCE plugin.
*/

Once done you should be able to select this plugin in WordPress and activate it. All the code from now on can be pasted inside this file.

So, back to enabling some built-in but hidden buttons. Here’s the code that allows us to enable the 3 buttons I mentioned:

add_filter( 'mce_buttons_2', 'my_tinymce_buttons' );
function my_tinymce_buttons( $buttons ) {
    $buttons[] = 'superscript';
    $buttons[] = 'subscript';
    $buttons[] = hr;
    return $buttons;
}

To know which buttons can be added and what they are called, take a look at the list found in the TinyMCE documentation for controls.

Creating Our Own Buttons

How about creating our own buttons from scratch? Many websites use Prism for code highlighting which uses a very semantic approach to marking up code segments. You have to wrap your code within <code> and <pre> tags, something like this:

<pre><code>$variable = 'value'</code></pre>

Let’s create a button which will do this for us!

This is a three-step process. You will need to add a button, load a javascript file and actually write the content of the Javascript file. Let’s get started!

Adding the button and loading the Javascript file is pretty straightforward, here’s the code I used to get it done:

add_filter( 'mce_buttons', 'pre_code_add_button' );
function pre_code_add_button( $buttons ) {
    $buttons[] = 'pre_code_button';
    return $buttons;
}
add_filter( 'mce_external_plugins', 'pre_code_add_javascript' );
function pre_code_add_javascript( $plugin_array ) {
	$plugin_array['pre_code_button'] = get_template_directory_uri() . '/tinymce-plugin.js';
	return $plugin_array;
}

When I see tutorials about this I frequently see 2 problems.

They neglect to mention that the button name added in the pre_code_add_button() function must be the same as the key for the $plugin_array variable in the pre_code_add_javascript() function. We will also need to use the same string in our Javascript later on.

Some tutorials also use an additional admin_head hook to wrap everything up. While this will work, it is not required and since the Codex does not use it, it should probably be avoided.

The next step is to write some Javascript to implement our functionality. Here’s what I used to get the <pre> and <code> tags output all at once.

(function() {
    tinymce.PluginManager.add('pre_code_button', function( editor, url ) {
        editor.addButton( 'pre_code_button', {
            text: 'Prism',
            icon: false,
            onclick: function() {
            var selected = tinyMCE.activeEditor.selection.getContent();
            var content = '<pre><code>' + selected + '</code></pre>';
            editor.insertContent( content + "\n" );
            }
        });
    });
})();

Most of this is dictated by how a TinyMCE plugin is supposed to be coded, you can find some information about that in the TinyMCE documentation. For now, all you need to know is that the name of your button (pre_code_button) should be used in line 2 and 3. The value of "text" in line 4 will be displayed if you do not use an icon (we’ll take a look at adding icons in a moment).

The onclick method dictates what this button does when it is clicked. I want to use it to wrap selected text within the HTML structure discussed earlier.

The selected text can be grabbed using tinyMCE.activeEditor.selection.getContent(). Then, I wrap the elements around it and insert it, replacing the highlighted content with the new element. I’ve also added a new line so I can easily start writing after the code element.

If you want to use an icon I suggest selecting one from the Dashicons set which ships with WordPress. The Developer Reference has a great tool for finding icons and their CSS/HTML/Glyph. Find the code symbol and note the unicode underneath it: f475.

We’ll need to attach a stylesheet to our plugin and then add a simple style to display our icon. First up, let’s add our style to WordPress:

add_action( 'admin_enqueue_scripts', 'pre_code_styles' );
function pre_code_styles() {
	wp_enqueue_style( 'pre_code_button', plugins_url( '/style.css', __FILE__ ) );
}

Go back to the Javascript and next to the icon in the addButton function, replace “false” with a class you would like your button to have – I used pre_code_button.

Now create the style.css file in your plugin directory and add the following CSS:

i.mce-i-pre_code_button:before {
	font-family:dashicons;
	content: "\f475";
}

Note that the button will receive the mce-i-[your class here] class which you can use to target and add styles. Specify the font as dashicons and the content using the unicode value from earlier.

Using TinyMCE Elsewhere

Plugins often create textareas for entering longer text, wouldn’t it be great if we could use TinyMCE there as well? Of course we can, and it’s pretty easy. The wp_editor() function allows us to output one anywhere in admin, here’s how it looks:

wp_editor( $initial_content, $element_id, $settings );

The first parameter sets the initial content for the box. This could be used to load an option from the database, for example. The second parameter sets the HTML element’s ID. The third parameter is an array of settings. To read about the exact settings you can use, take a look at the wp editor documentation.

The most important setting is the textarea_name. This populates the name attribute of the textarea element, allowing you to save the data easily. Here’s how my editor looks when used in an options page:

$settings = array( 'textarea_name' => 'buyer_bio' );
wp_editor( get_option('buyer_bio'), 'buyer_bio', $settings );

This is equivalent to writing the following code, which would result in a simple textarea:

<textarea id='buyer_bio' class='buyer_bio'><?php get_option( 'buyer_bio' ) ?></textarea>

Conclusion

The TinyMCE editor is a user-friendly way of allowing users more flexibility when entering content. It allows those who don’t want to format their content to just type it up and be done with it, and those who want to fiddle around with it to spend as much time as they need getting it just right.

Creating new buttons and functionality can be done in a very modular way, and we’ve only just scratched the surface of the possibilities. If you know of a particularly good TinyMCE plugin or use case which has helped you a lot, do let us know in the comments below!

WebsiteFacebookTwitterInstagramPinterestLinkedInGoogle+YoutubeRedditDribbbleBehanceGithubCodePenWhatsappEmail