As developers working with WordPress, we’ve seen the shift from the classic editor to the modern Block Editor. One powerful features we get to work with is it the Formatting Toolbar API, which allows us to add custom controls to the inline formatting toolbar of rich text fields in our blocks.
What Is the Formatting Toolbar API?
The Formatting Toolbar API lets us add custom inline buttons (like bold, italic, links, etc) to the toolbar that appears when we highlight text inside a rich text block. This API is part of the @wordpress/rich-text
and @wordpress/format-library
packages.
With this, we can introduce custom formats like highlighting text or adding special tooltips to create a more tailored content editing experience for our users.
Example: Adding a “Highlight” Button to the Toolbar
1. Register the Format Type
We’ll use registerFormatType
from @wordpress/rich-text
.
// my-custom-highlight.js import { registerFormatType, toggleFormat } from '@wordpress/rich-text'; import { RichTextToolbarButton } from '@wordpress/block-editor'; import { Fragment } from '@wordpress/element'; import { __ } from '@wordpress/i18n'; import { formatBold } from '@wordpress/icons'; registerFormatType('my-plugin/highlight', { title: __('Highlight', 'my-plugin'), tagName: 'mark', className: 'highlighted-text', edit({ isActive, value, onChange }) { return ( <Fragment> <RichTextToolbarButton icon={formatBold} title={__('Highlight', 'my-plugin')} onClick={() => { onChange(toggleFormat(value, { type: 'my-plugin/highlight', })); }} isActive={isActive} /> </Fragment> ); }, });
2. Enqueue the Script
In our plugin or theme functions.php
, enqueue the script using enqueue_block_editor_assets
.
function my_plugin_enqueue_formatting_toolbar() { wp_enqueue_script( 'my-custom-highlight', plugin_dir_url(__FILE__) . 'my-custom-highlight.js', [ 'wp-rich-text', 'wp-element', 'wp-block-editor', 'wp-i18n' ], false, true ); } add_action('enqueue_block_editor_assets', 'my_plugin_enqueue_formatting_toolbar');
3. Add Some Styling
Add a custom style so the highlighting is visible.
.mark.highlighted-text { background-color: yellow; padding: 0 2px; }
Conclusion
The Formatting Toolbar API gives us a flexible way to extend the WordPress editing experience. Whether we’re adding highlights, tooltips, or custom shortcodes, this API is a powerful tool in our WordPress development toolkit.
Leave a Reply