How To Disable WordPress Heartbeat With Code

Ever since WordPress version 3.6,  a new feature called the Heartbeat API was introduced into the WordPress framework. Basically, the Heartbeat API communicates live from your browser to the server in order for WordPress to manage admin sessions, page & post revisions, and handle auto saving. I am going to show you how to easily disable the Heartbeat API and keep your server safe from excessive CPU usage.

If you have ever worked in WordPress with multiple admin users and saw editing was locked due to another user on that admin page, then you have experienced some of the Heartbeat API. With teams of people, this is a great feature, but it can tax the server and increase CPU usage. If you happen to leave your admin dashboard open in a browser for any significant time, your server is getting pinged every 60 seconds for no real benefit. If the dashboard is out of focus, the ping time is around 120 seconds.  So having the dashboard open for a half-hour results in over 25-30 PHP script executions that don’t need to be executed.

The good news is that disabling the WordPress Heartbeat API with code is a very simple process.   The quickest and easiest way would be to install the Heartbeat Control plugin by Jeff Matson.  This plugin will basically allow you to change the timing of the Heartbeat API and where it fires.  But if you don’t want to install a plugin, then stopping the Heartbeat API with code is a simple process.

Disable the WordPress Heartbeat API completely:


function ninja_stop_heartbeat() {
    wp_deregister_script('heartbeat');
}
add_action( 'init', 'ninja_stop_heartbeat', 1 );

Disable the WordPress Heartbeat API on Dashboard page (index.php):


function ninja_stop_heartbeat() {
    global $pagenow;
    if ( $pagenow == 'index.php' ){
        wp_deregister_script('heartbeat');
    }
}
add_action( 'init', 'ninja_stop_heartbeat', 1 );

Disable the WordPress Heartbeat API on all pages but post.php & post_new.php:


function ninja_stop_heartbeat() {
    global $pagenow;
    if ( $pagenow != 'post.php' && $pagenow != 'post-new.php' ){
        wp_deregister_script('heartbeat');
    }
}
add_action( 'init', 'ninja_stop_heartbeat', 1 );

NOTE: Keep in mind that WordPress may use the Heartbeat API much more in the future. Keep an active eye on WordPress’s development to see if you need to adjust your code if a new feature is turned on.

Leave a Reply

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