Keyboard Key (kbd) Button in the Block Toolbar
Adds a "Keyboard key" format to the text toolbar that wraps text in <kbd> and styles it like a key cap, for tutorials with shortcuts such as Ctrl + S.
Opens WPIDE on
Code
add_action( 'enqueue_block_editor_assets', function () {
wp_register_script( 'wpide-kbd-format', false, array( 'wp-rich-text', 'wp-block-editor', 'wp-element' ), '1.0', true );
wp_enqueue_script( 'wpide-kbd-format' );
wp_add_inline_script( 'wpide-kbd-format', <<<'JS'
( function ( wp ) {
wp.richText.registerFormatType( 'wpide/kbd', {
title: 'Keyboard key',
tagName: 'kbd',
className: null,
edit: function ( props ) {
return wp.element.createElement( wp.blockEditor.RichTextToolbarButton, {
icon: 'editor-code',
title: 'Keyboard key',
isActive: props.isActive,
onClick: function () {
props.onChange( wp.richText.toggleFormat( props.value, { type: 'wpide/kbd' } ) );
}
} );
}
} );
} )( window.wp );
JS
);
} );
$wpide_kbd_css = 'kbd{display:inline-block;padding:.1em .45em;font:600 .85em/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;border:1px solid #c3c4c7;border-bottom-width:3px;border-radius:4px;background:#f6f7f7;color:#1d2327;white-space:nowrap;}';
add_action( 'enqueue_block_assets', function () use ( $wpide_kbd_css ) {
wp_register_style( 'wpide-kbd', false, array(), '1.0' );
wp_enqueue_style( 'wpide-kbd' );
wp_add_inline_style( 'wpide-kbd', $wpide_kbd_css );
} );
Notes
Find it in the toolbar's "More" (chevron) menu.
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.