WordPress Gutenberg Editor: Applying a custom format to a text selection

Needless to say, WordPress’ Gutenberg editor has made life easy for a lot of people. You no more need additional plugins, shortcodes, and theme customizations to format your posts to fit your various needs.

I switched to Gutenberg to write posts for this blog recently. Since I write tech tutorials often, I needed a way to demarcate lines of codes and references to buttons and other UI elements so that following my tutorials would be easy. Even though you have a native format to highlight codes, I needed a different way of showing UI elements such as button texts. For instance, if I want the reader to click on a certain button called Add, I should be able to make it stand out.

Of course, an easy way of doing this is to use custom HTML. But I wanted a reusable method. A button in the formatting toolbar that could toggle such a text format would fit the bill perfectly, I thought.

When I researched a way to do it, I came across WordPress’s Format API that lets you add buttons to the toolbar. This was exactly what I was looking for and WordPress, as they have always done, never disappointed me.

In this blog post, let’s see how to get this done. What we are going to do is to create a WordPress plugin that would add a button to the toolbar. This button will toggle the text formatting.

To create a WordPress plugin, first, create a folder and name it. I named it as SpecialTag since that was going to be my plugin’s name. Inside the folder, create three files:

  1. Specialtag.php
  2. Specialtag.js
  3. Specialtag.css

The php file will provide the necessary details regarding your plugin to WordPress such as the name of your plugin, its version, author details, etc. In addition, you will be adding your JavaScript and CSS files to WordPress through this file.

To begin with, open a php tag and in a block comment, add the name of the plugin, the author’s name, etc.

<?php

/**

 * Plugin Name: Special Tag

 * Author: Theviyanthan K.

 * Author URI: http://www.thearmchaircritic.org

 */

Then, let’s register our script and list the JavaScript dependencies such as wp-rich-text, wp-editor, and wp-element. As you would see later, we would be using these JavaScript modules to create our toolbar button.

function my_custom_format_script_register() {

    wp_register_script(

        'special-tag-js',

        plugins_url( 'specialtag.js', __FILE__ ),

        array( 'wp-rich-text','wp-editor','wp-element' )

    );

}

add_action( 'init', 'my_custom_format_script_register' );

Once registered, we can load the script file. Since we are applying a custom text format, we need a CSS file as well. Let’s load that too.

function my_custom_format_enqueue_assets_editor() {

    wp_enqueue_script( 'special-tag-js' );

    wp_enqueue_style("special-tag-css",plugins_url("SpecialTag/specialtag.css"),array(),'1.0.0','all');

}
add_action( 'enqueue_block_editor_assets', 'my_custom_format_enqueue_assets_editor' );

The above function loads the script and css file only in the block editor page. We need the js file in the block editor but the css file is needed in our frontend pages as well. So, let’s load the css file when our WordPress blog is loaded.

function specialTagCSS(){    
wp_enqueue_style("special-tag-css",plugins_url("SpecialTag/specialtag.css"),array(),'1.0.0','all');

}

add_action( 'wp_enqueue_scripts', 'specialTagCSS' );

This completes our php file and we would no more be touching it. Save, and open the js file.

It is this file that will be creating the button and then registering the button with the toolbar. This file will also specify the CSS class our formatted text is supposed to use.

To begin writing our js script, let’s create this basic scaffolding.

( function( wp ) {

} )( window.wp );

Then, inside the function, let’s create a button.

var SpecialTagButton = function( props ) {
        return wp.element.createElement(
            wp.editor.RichTextToolbarButton, {
                icon: 'image-flip-horizontal',
                title: 'Special Tag',
                onClick: function() {
                    props.onChange( wp.richText.toggleFormat(
                        props.value,
                        { type: 'special-tag/output' }
                    ) );
                },
                isActive: props.isActive,
            }
        );
    }

Here, you can change the icon of your button, its title, and its click function. You can find the list of icons you can use here. The type key’s value is important and we will be using it when creating our text format.

After we create our button, we have to create a text format type. This format will have a unique style which can be toggled by the button we just created.

   wp.richText.registerFormatType(
        'special-tag/output', {
            title: 'Special Tag',
            tagName: 'span',
            className: 'special-tag',
            edit: SpecialTagButton,
        }
    );

The first argument is the type that we specified when creating the button. What we are doing here is to create an HTML tag with a certain CSS class. The text we apply this formatting to will be enclosed by this tag. So, specify the title, tag name, and the class name. Supply the button that we created in the previous step as the value for the edit key.

Now, we have created our button and the text format. The only step that is left is to create a CSS class to format our text. So, open the CSS file and create a class with the name of the class that we used to create the text format.

In this class, you can insert any CSS styling you want. I wanted a blue box with rounded corners. So, I inserted the following:

.special-tag{
    background-color: #1a73e8;
    padding: 3px;
    border-radius: 3px;
    color: white;
    font-size: 0.9em;
}

Our plugin is now ready and all that we need to do is to place it in the plugin directory of our WordPress installation. Copy the folder and place it in wp-content/plugins/.

Now, if you go to the plugins page of WordPress, you will be able to see your plugin.

Click on Activate and you will be able to find your button in the toolbar.

The button can now be used to toggle the text format wherever you want.

The formatted text in the Gutenberg editor
The formatted text in the blog post

The plugin’s source code is available in this Git repo.

1 Comment

  1. Hi mate,
    I want to add something to selected text via clicking formatting button. How can I do that?
    Thanks a lot expert developer 🙂

Leave a Reply

placeholder="comment">