Creating a Custom CKEditor Button

With only a little bit of code, we can add a new button via CKEditor 4 Plugin

In CKEditor 4, the buttons on the toolbar are made up of various plugins, located in its /plugins/ folder. In our case, I needed to add a custom button that, when viewing the source, would look as such:

<p class="h2">H2 Heading</p>

It's a bit of a strange use-case, but it's for a website in which the software strips (sanitizes) headings, as it's built as community software and we don't want members adding headers. We then use JavaScript to convert this <p> tag into an actual <h2> tag where we want to allow it (an articles section that only team members can post to). In case you're curious, here's the jQuery:

/* Replace headings for semantic articles using jQuery */
$('p.h2').replaceWith(function() { 
    return $('<h2>').addClass('heading').append($('<span>').html($(this).html()));
$('p.h3').replaceWith(function() { 
    return $('<h3>').addClass('h3').append($('<span>').html($(this).html()));

Most search engines will be able to see these headings as normal, so SEO-wise we're in the clear.

Instead of always going into CKEditor's source tab and typing that HTML in manually every time, I figured it would be best to create a little plugin that added a heading button using the p tags with its class.

CKEditor 4 Plugin

Now we can get started. In CKEditor 4, the plugin's folder name needs to be the same as the plugin's name, otherwise it won't be recognized. We'll make a new folder in the /plugins/ directory called pheadings.

The structure will look like this:

  1. /plugins/pheadings
  2. /plugins/pheadings/icons
  3. /plugins/pheadings/icons/pheadingh2.png
  4. /plugins/pheadings/plugin.js

Let's open up the plugin.js file and add:

CKEDITOR.plugins.add( 'pheadings', {
    icons: 'pheadingh2',
    init: function( editor ) {
        editor.addCommand( 'insertPHeadingH2', {
            exec: function( editor ) {
                editor.insertHtml( '<p class="h2">Heading</p><p>&nbsp;</p>' );

And then we'll need to add this to the toolbar itself. This is added to the same init from above.

editor.ui.addButton( 'PHeadingH2', {
    label: 'Insert Heading',
    command: 'insertPHeadingH2',
    toolbar: 'insert'

Finally, we can load the plugin. In the CKEDITOR.config.extraPlugins configuration, add the plugin name along with the other plugins you're running.

config.extraPlugins = 'pluginA,pluginB,pheadings';

There are no comments to display.