Keyboard shortcut for updating a page or post?

I was curious about this and checked the Codex on keyboard shortcuts, but didn’t find it mentioned there.

I searched and found out that this seems to be already solved, e.g. here and here.

I haven’t tested out these other plugins so I’m not sure how they solve it, but I decided to take on the challenge and see how this could be solved 😉

So here’s my hack for creating shortcuts for:

ctrl+s : Save Draft
ctrl+p : Publish / Update

with the following test plugin that runs within the after_wp_tiny_mce hook:

/**
 * Plugin Name: Testing ctrl+s and ctrl+p for saving and publishing posts.
 * Plugin URI:  https://wordpress.stackexchange.com/a/199411/26350
 */
add_action( 'after_wp_tiny_mce', function()
{?><script>
    ( function ( $ ) {
        'use strict';
        $( window ).load( function () {
            wpse.init();
        });
        var wpse = {
            keydown : function (e) {
                if( e.ctrlKey && 83 === e.which ) {
                    // ctrl+s for "Save Draft"
                    e.preventDefault();
                    $( '#save-post' ).trigger( 'click' ); 
                } else if ( e.ctrlKey && 80 === e.which ) {
                    // ctrl+p for "Publish" or "Update"
                    e.preventDefault();
                    $( '#publish' ).trigger( 'click' );
                }
            },
            set_keydown_for_document : function() {
                $(document).on( 'keydown', wpse.keydown );
            },
            set_keydown_for_tinymce : function() {
               if( typeof tinymce == 'undefined' )
                   return;
               for (var i = 0; i < tinymce.editors.length; i++)
                   tinymce.editors[i].on( 'keydown', wpse.keydown );
           },
           init : function() {
               wpse.set_keydown_for_document();
               wpse.set_keydown_for_tinymce();
           }
       }                                                        
    } ( jQuery ) );
    </script><?php });

I added the wpse.keydown event-callback to every tinymce editor on the page, so the shortcuts would be available from there too.

Note that I use the after_wp_tiny_mce hook, as a convinient test-hook on a vanilla install, since we’re dealing with the tinymce javascript object.
When we ship such a plugin, we should enqueue it from a .js file, as usual.

We could also use the SetupEditor event of tinymce, as mentioned here by @bonger, but here I’ve added an extra check to see if tinymce is defined, to avoid javascript error on pages where it’s not defined:

// Keydown for tinymce
if( typeof tinymce != 'undefined' )
{
    tinymce.on( 'SetupEditor', function (editor) {
        wpse.set_keydown_for_tinymce();
    });
}
// Keydown for document
wpse.set_keydown_for_document();

We could probably setup native tinymce shortcuts as well.

This might need some testing & adjustments, but it seems to work on my install.

Leave a Comment