Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.