Updating WordPress Posts and Pages with CTRL+S

09 Mar 2011

Updating WordPress Posts and Pages with CTRL+S


I spend a lot of time coding. a lot. So much so, that when I write posts and pages on my WordPress sites and go to save it, I hit Ctrl+S (Cmd+S on Mac), which is the short-key to save in pretty much any program ever made. It can get frustrating to save and have to stop, exit out of the popup window trying to save the website locally, and then hit the Update button. So, this snippet covers how to detect when a page is loaded, output scripts, see when a user presses multiple buttons across operating systems, stop the default reaction from the browser, and finally activate a button.

<?php
/*
 Plugin Name: CMD+S
 Plugin URI:  http://mikepayne.co
 Description: Saves post/page/cpt with keyboard shortcut cmd+s / ctrl+s
 Version:     0.1
 Author:      Mike Payne
 Author URI:  http://mikepayne.co
*/
/**
 * Enqueue javascript only on edit post page.
 * 
 * @access public
 * @param string $hook_suffix
 * @return void
 */
function cmds_admin_enqueue($hook_suffix) {
   if( 'post.php' == $hook_suffix || 'post-new.php' == $hook_suffix ) {
     wp_enqueue_script( 'cmds_js', ( 'cmd-s.js', __FILE__ ), array( 'jquery' ));
  }
}
add_action( 'admin_enqueue_scripts', 'cmds_admin_enqueue' );
jQuery(window).bind('keydown', function(event) {
	if (event.ctrlKey || event.metaKey) {
		if(String.fromCharCode(event.which).toLowerCase() == 's') {
			// stop the page from trying to download
			event.preventDefault();
			// trigger page update or page publish
			jQuery('#publish').click();
		}
	}
});

The function I’ve put here pretty much just includes a javascript file in the footer of the admin panel, but only on post.php or post-new.php. This will allow us to access the pages used to either publish or update the page or post. This jQuery function detects when the user presses the Ctrl key along with S(key 115). On a Mac OS, the browser returns cmd+s as key 19, so we can make it cross os by including that as well. If neither of those statements is true, we can return true and allow the key to be presses in it’s default action. If it’s false, that means either Ctrl+s or Cmd+s was pressed sp we should click the button with the id of Publish. This will submit the page to be updated or published for the first time.

This isn’t quite enough though, because the browser will still try to save the webpage. To stop the browsers default action on a JavaScript command, we use the event.preventDefault() method, and return false.

Leave a Reply

Your email address will not be published. Required fields are marked *