Performance PHP Beginner

Control the Heartbeat API Safely

Turn off the Heartbeat API for logged-out visitors and slow it down in wp-admin, without breaking autosave, post locking or login expiry warnings.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 14 lines
// 1. Logged-out visitors never need Heartbeat.
add_action( 'wp_enqueue_scripts', function (): void {
	if ( ! is_user_logged_in() ) {
		wp_deregister_script( 'heartbeat' );
	}
}, 100 );

// 2. Slow it down: every 60 seconds in the editor, every 120 seconds elsewhere.
add_filter( 'heartbeat_settings', function ( array $settings ): array {
	$screen               = function_exists( 'get_current_screen' ) ? get_current_screen() : null;
	$is_editor            = $screen && 'post' === $screen->base;
	$settings['interval'] = $is_editor ? 60 : 120;
	return $settings;
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

The Heartbeat API sends a request to admin-ajax.php every 15 to 60 seconds while a page is open. It powers autosave, post locking (the “someone else is editing” warning), the “your session expired” login pop-up and live updates in some plugins. On shared hosting, many open tabs can add up to real server load.

How it works

The first part removes Heartbeat for visitors who aren’t logged in. Nothing on the front end needs it for them.

The second part slows Heartbeat down rather than turning it off. In the post editor it runs every 60 seconds, so autosave and post locking keep working. On every other admin screen it runs every 120 seconds, the slowest WordPress allows, which still lets the session-expired pop-up appear.

Why not turn it off in wp-admin?

An earlier version of this snippet deregistered Heartbeat on every admin screen except the editor. That stopped the login-expiry warning, so people lost unsaved work in other screens, and broke plugins that use Heartbeat for live data, such as WooCommerce’s order screens. Slowing it down saves most of the load without those side effects.

This replaces our older “Disable the Heartbeat API on the Frontend” snippet, which did the same as part 1.

How to test it

Open the dashboard with DevTools’ Network panel filtered to admin-ajax. Requests with action=heartbeat should arrive about two minutes apart. In the post editor they should be about a minute apart, and in a logged-out window there should be none.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only