Abbreviation Button in the Block Toolbar
Adds an "Abbreviation" option to the text formatting menu that wraps selected text such as "SEO" in an abbr tag with its full meaning, shown as a tooltip and read by screen readers.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-abbr-format', false, array( 'wp-rich-text', 'wp-element', 'wp-block-editor' ), '1.0', true );
wp_enqueue_script( 'wpide-abbr-format' );
wp_add_inline_script( 'wpide-abbr-format', <<<'JS'
( function ( wp ) {
var el = wp.element.createElement;
var name = 'wpide/abbr';
wp.richText.registerFormatType( name, {
title: 'Abbreviation',
tagName: 'abbr',
className: 'wpide-abbr',
attributes: { title: 'title' },
edit: function ( props ) {
return el( wp.blockEditor.RichTextToolbarButton, {
icon: 'editor-textcolor',
title: 'Abbreviation',
isActive: props.isActive,
onClick: function () {
if ( props.isActive ) {
props.onChange( wp.richText.removeFormat( props.value, name ) );
return;
}
var meaning = window.prompt( 'What does this abbreviation stand for?' );
if ( meaning ) {
props.onChange( wp.richText.applyFormat( props.value, { type: name, attributes: { title: meaning } } ) );
}
}
} );
}
} );
} )( window.wp );
JS
);
} );
Notes
Select the abbreviation, open the dropdown arrow in the toolbar and choose Abbreviation; click it again on marked text to remove it.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.