WordPress Slow Database? Find Large Autoloaded Options

A slow WordPress database is often caused by autoloaded options, not by a bad query. On every request, WordPress loads every option marked for autoload in a single query and keeps them in memory. This includes front-end pages, admin screens, AJAX calls and cron. Plugins that store logs, caches or big settings arrays as autoloaded options make that query heavier on every page, even pages that never use the data.

The snippet below adds a Tools → Autoloaded options screen. It shows the total autoloaded size, lists the largest autoloaded options, and gives each one a Turn off autoload button. The option and its value stay in the database. WordPress just stops loading it on every request and fetches it only when code asks for it.

The snippet

Put it in a small plugin, an mu-plugin, or your theme’s functions.php. Only users with manage_options can see the screen or use the button, and every button is protected by a nonce.

<?php
/**
 * Plugin Name: DPC Autoloaded Options Report
 * Description: Tools > Autoloaded options. Lists the largest autoloaded options and lets admins turn autoload off.
 */

function dpc_autoload_protected_options(): array {
	global $wpdb;
	$core = array(
		'siteurl', 'home', 'blogname', 'blogdescription', 'active_plugins',
		'template', 'stylesheet', 'cron', 'rewrite_rules', 'permalink_structure',
		'sidebars_widgets', 'db_version', 'WPLANG', $wpdb->prefix . 'user_roles',
	);
	return (array) apply_filters( 'dpc_autoload_protected_options', $core );
}

function dpc_autoload_get_largest( int $limit = 25 ): array {
	global $wpdb;
	$values = wp_autoload_values_to_autoload();
	$in     = implode( ',', array_fill( 0, count( $values ), '%s' ) );
	$sql    = $wpdb->prepare(
		"SELECT option_name, LENGTH(option_value) AS size FROM {$wpdb->options} WHERE autoload IN ($in) ORDER BY LENGTH(option_value) DESC LIMIT %d",
		...array_merge( $values, array( max( 1, $limit ) ) )
	);
	$rows = $wpdb->get_results( $sql, ARRAY_A );

	return array_map(
		static fn( array $row ): array => array(
			'name' => (string) $row['option_name'],
			'size' => (int) $row['size'],
		),
		$rows ?: array()
	);
}

function dpc_autoload_total_size(): int {
	global $wpdb;
	$values = wp_autoload_values_to_autoload();
	$in     = implode( ',', array_fill( 0, count( $values ), '%s' ) );
	$sql    = $wpdb->prepare(
		"SELECT SUM(LENGTH(option_value)) FROM {$wpdb->options} WHERE autoload IN ($in)",
		...$values
	);
	return (int) $wpdb->get_var( $sql );
}

function dpc_autoload_disable( string $name ): bool {
	global $wpdb;
	if ( '' === $name || in_array( $name, dpc_autoload_protected_options(), true ) ) {
		return false;
	}
	$current = $wpdb->get_var(
		$wpdb->prepare( "SELECT autoload FROM {$wpdb->options} WHERE option_name = %s", $name )
	);
	if ( null === $current || ! in_array( $current, wp_autoload_values_to_autoload(), true ) ) {
		return false; // Missing, or already not autoloaded.
	}
	return wp_set_option_autoload( $name, false );
}

function dpc_autoload_handle_off(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		wp_die( esc_html( 'You are not allowed to do this.' ), 403 );
	}
	$name = isset( $_POST['option'] ) ? sanitize_text_field( wp_unslash( $_POST['option'] ) ) : '';
	check_admin_referer( 'dpc_autoload_off_' . $name );

	$done = dpc_autoload_disable( $name );

	wp_safe_redirect(
		add_query_arg(
			array( 'page' => 'dpc-autoload', 'dpc_done' => $done ? '1' : '0' ),
			admin_url( 'tools.php' )
		)
	);
	exit;
}
add_action( 'admin_post_dpc_autoload_off', 'dpc_autoload_handle_off' );

function dpc_autoload_render_page(): void {
	if ( ! current_user_can( 'manage_options' ) ) {
		return;
	}
	$rows      = dpc_autoload_get_largest( (int) apply_filters( 'dpc_autoload_list_limit', 25 ) );
	$protected = dpc_autoload_protected_options();
	$action    = admin_url( 'admin-post.php' );

	echo '<div class="wrap"><h1>' . esc_html( 'Autoloaded options' ) . '</h1>';

	if ( isset( $_GET['dpc_done'] ) ) {
		$ok = '1' === sanitize_key( wp_unslash( $_GET['dpc_done'] ) );
		printf(
			'<div class="notice notice-%1$s is-dismissible"><p>%2$s</p></div>',
			$ok ? 'success' : 'error',
			esc_html( $ok ? 'Autoload turned off.' : 'Nothing changed: the option is protected, missing or already off.' )
		);
	}

	printf(
		'<p>%s <strong>%s</strong></p>',
		esc_html( 'Total size of autoloaded options:' ),
		esc_html( (string) size_format( dpc_autoload_total_size(), 1 ) )
	);

	echo '<table class="widefat striped"><thead><tr><th>Option</th><th>Size</th><th>Action</th></tr></thead><tbody>';
	foreach ( $rows as $row ) {
		echo '<tr><td><code>' . esc_html( $row['name'] ) . '</code></td>';
		echo '<td>' . esc_html( (string) size_format( $row['size'], 1 ) ) . '</td><td>';
		if ( in_array( $row['name'], $protected, true ) ) {
			echo esc_html( 'Core option, kept' );
		} else {
			echo '<form method="post" action="' . esc_url( $action ) . '">';
			echo '<input type="hidden" name="action" value="dpc_autoload_off">';
			echo '<input type="hidden" name="option" value="' . esc_attr( $row['name'] ) . '">';
			wp_nonce_field( 'dpc_autoload_off_' . $row['name'], '_wpnonce', false );
			echo '<button type="submit" class="button button-small">' . esc_html( 'Turn off autoload' ) . '</button></form>';
		}
		echo '</td></tr>';
	}
	echo '</tbody></table></div>';
}

function dpc_autoload_admin_menu(): void {
	add_management_page(
		'Autoloaded options',
		'Autoloaded options',
		'manage_options',
		'dpc-autoload',
		'dpc_autoload_render_page'
	);
}
add_action( 'admin_menu', 'dpc_autoload_admin_menu' );

How it works

  • Since WordPress 6.6 the autoload column holds more than yes/no. It can also be on, off, auto, auto-on and auto-off. wp_autoload_values_to_autoload() returns the values that actually get loaded, so the queries count exactly what WordPress loads on boot, old values included.
  • dpc_autoload_get_largest() sorts those rows by LENGTH(option_value), and dpc_autoload_total_size() adds them up. Both are prepared queries.
  • Each button posts to admin-post.php. The handler checks manage_options, then verifies a nonce tied to that option name, and then calls core’s wp_set_option_autoload( $name, false ). Core sets the row to off and clears the cached alloptions (including a persistent object cache).
  • dpc_autoload_disable() refuses core options like siteurl, active_plugins, cron and rewrite_rules, options that don’t exist, and options that are already off.

Customise it

  • Show more rows: add_filter( 'dpc_autoload_list_limit', fn() => 50 );
  • Protect your own options from the button: add_filter( 'dpc_autoload_protected_options', fn( $list ) => [ ...$list, 'my_plugin_settings' ] );
  • Use dpc_autoload_disable( 'option_name' ) in a one-off WP-CLI wp eval if you’d rather not click.

Gotchas

  • Turning autoload off for an option that is read on every page swaps one large load for one extra query per page. Use the button on options that only matter on a few screens, such as plugin logs, import data, leftovers from removed plugins, or big caches used only in the admin.
  • A plugin that saves its option again with update_option( $name, $value, true ) will turn autoload back on. Check the list again after plugin updates.
  • Large, never-expiring transients are autoloaded too. If they are stale, delete them instead. See WordPress Clear Transients With One Admin Bar Button, and why set_transient may not behave as expected.
  • Sizes come from LENGTH(), so treat them as close estimates. On multisite the screen shows the options table of the current site only.
  • If the admin is slow rather than the front end, also look at the Heartbeat API.

Snippet poll. Should this snippet be in the Scripts Organizer library for one-click import? 10 votes put it there.

0 of 10 votes

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You’ll also get DPlugins product updates. No spam, and you can unsubscribe anytime.

// newsletter

Three tested WordPress snippets a week

Blocks, security, performance, Tailwind, PHP and React. Copy, paste, ship. You'll also get DPlugins product updates. No spam, and you can unsubscribe anytime.