Block Editor: Cmd+Shift+Plus to Toggle Block Inserter

Block editor cmdshiftplus to toggle block inserter image

Why limit yourself to default keyboard shortcuts in the Block Editor when you could add extra ones that you’ll probably never remember? (but for me this one’s better 👟 )

What it does…

Allows Mac users to press Cmd+Shift+Plus and see the Block Inserter.

Why it does it…

There was a time when I found this really useful. Sometimes I’m doing a lot of repetitive work in the WordPress Block Editor, and will toggle this on. Yes, by default, WP offers Cmd+Alt+T or Cmd+Alt+Y for inserting before (T) or after (Y), but I like mine better. And the default is less comfy. But also mine doesn’t work sometimes. Still figuring that out.

How it does it…

When the Block Editor loads, this adds a javascript that listens for keydown, then triggers a click of the open/close Block Inserter button.

See the code…

<?php

// Block Editor: Cmd+Shift+Plus to Toggle Block Inserter
// https://snipsnip.pro/s/174
namespace n12UckiJ;
function block_editor_toggle_inserter_shortcut(){
	if ( !function_exists( '\get_current_screen' ) ) { return false; }
	$screen = \get_current_screen();
	if ( method_exists( $screen, 'is_block_editor' ) && $screen->is_block_editor() ) {
?>
	<script>
    let n12UckiJ = {};
	n12UckiJ.domReady = cb => {
		"interactive" === document.readyState || 
		"complete" === document.readyState ? 
		cb() : document.addEventListener("DOMContentLoaded", cb)
	};
	n12UckiJ.domReady(() => {
        setTimeout(()=>{
            document.addEventListener("keydown", function(e) {
                if (e.shiftKey && e.metaKey && e.keyCode === 187) {
                    e.preventDefault();
                    let el = document.querySelector('button[aria-label="Toggle block inserter"]');
                    el && el.click();
                }  
            });
			console.log('Block Editor: Cmd+Shift+Plus to Toggle Block Inserter [SnipSnip.pro]');    
        },6000);
	});
	</script>
<?php
	}
}
\add_action( 'admin_print_footer_scripts', '\n12UckiJ\block_editor_toggle_inserter_shortcut' );