WP Tuts Hub

Browse

  • Home
  • Categories
    • WordPress & AI
    • WordPress Security
    • WordPress Troubleshooting
    • WordPress Tips and Tricks
    • SSH (Secure Shell)
    • WordPress Insights
    • WordPress Common Facts
  • Series Tutorials
  • My Plugins
  • Contact Me
  • About WP Tuts Hub
Home/WordPress Troubleshooting/Fix WordPress Memory Exhausted Error
WordPress Troubleshooting
By Md. Zubaer Ahammed November 16, 2026

Fix WordPress Memory Exhausted Error

  • fatal error
  • memory_limit
  • PHP-FPM
  • WP-CLI
  • wp-config.php
Fix WordPress Memory Exhausted Error

The WordPress memory exhausted error is a PHP fatal, not a WordPress bug. When a request prints Allowed memory size of 268435456 bytes exhausted (tried to allocate 20480 bytes), PHP stopped at the ceiling set for that process. Raising the ceiling is the easy half. Finding the code that filled it is the half that stops the error coming back next Tuesday.

The file named in the fatal error is the last straw, not the cause

Read the message in three parts before touching a file:

  • 268435456 bytes is the limit at the moment of death: 256 MB here. Compare it with what you assumed the limit was.
  • 20480 bytes is the allocation that failed. A small number means the request was already full and something earlier consumed the memory. A large number points at one operation: an image resize, a CSV import, a query pulling 50,000 rows.
  • wp-includes/… on line N is where it died, which is rarely where it started. Core code doing an ordinary thing on behalf of a plugin is the usual scene.

Visitors see There has been a critical error on this website. and nothing else, because WP_DEBUG_DISPLAY is off on any site you care about. The real message lands in the PHP error log, so start there rather than in the browser.

Read the limit PHP is actually running with before you change a single file

Three numbers matter and they are not the same number: the memory_limit PHP is running with, the WP_MEMORY_LIMIT constant WordPress wants, and WP_MAX_MEMORY_LIMIT, the higher ceiling WordPress uses for admin screens, AJAX, cron and image work. Save this as memory-report.php and run it with WP-CLI:

<?php
/**
 * Save as memory-report.php and run: wp eval-file memory-report.php
 */

// ini_set() returns false when the host has locked the value, for example with php_admin_value.
$changeable = false !== @ini_set( 'memory_limit', ini_get( 'memory_limit' ) );

printf( "memory_limit          : %s\n", ini_get( 'memory_limit' ) );
printf( "WP_MEMORY_LIMIT       : %s\n", defined( 'WP_MEMORY_LIMIT' ) ? WP_MEMORY_LIMIT : 'not defined' );
printf( "WP_MAX_MEMORY_LIMIT   : %s\n", defined( 'WP_MAX_MEMORY_LIMIT' ) ? WP_MAX_MEMORY_LIMIT : 'not defined' );
printf( "peak so far           : %s\n", size_format( memory_get_peak_usage( true ) ) );
printf( "changeable at runtime : %s\n", $changeable ? 'yes' : 'no (locked by the server)' );
printf( "loaded php.ini        : %s\n", php_ini_loaded_file() ? php_ini_loaded_file() : 'none' );

The last two lines decide your next move. If changeable at runtime says no, the host has locked memory_limit, usually with php_admin_value in the PHP-FPM pool, and ini_set(), including anything WordPress does on your behalf, is ignored. Editing wp-config.php in that situation is wasted effort; you need the server-side route below. php_ini_loaded_file() tells you which file to edit when you have access to it. Run the report through the web server as well as WP-CLI: the command line often has no limit at all, as the first output below shows.

memory-report.php run with WP-CLI (test site: WordPress 7.1.3, PHP 8.2):

memory_limit          : -1
WP_MEMORY_LIMIT       : 40M
WP_MAX_MEMORY_LIMIT   : 256M
peak so far           : 51 MB
changeable at runtime : yes
loaded php.ini        : none

The same report served by Apache, before and after locking the value with php_admin_value memory_limit 128M (test site: WordPress 7.1.3, PHP 8.2):

== web, default:
memory_limit          : 128M
changeable at runtime : yes
== web, php_admin_value memory_limit 128M:
memory_limit          : 128M
changeable at runtime : no (locked by the server)
Advertisement

Three places to raise the ceiling, and which one wins on your host

There are three routes that actually work, plus one that mostly does not. They are not interchangeable.

  • wp-config.php constants: portable, per site, no restart, no root. They only affect WordPress requests, which is usually exactly what you want. This is the right first move on shared hosting and most managed platforms, and it is the only route that travels with the site when you migrate it.
  • .user.ini: read by PHP-FPM and FastCGI per directory, so it covers every PHP file under the WordPress root, not just WordPress. Use it when ini_set() is blocked but you can still write files. Changes are cached for user_ini.cache_ttl (300 seconds by default), so it can look broken for five minutes.
  • php.ini or the FPM pool config: server-wide, needs root and a reload, and it is the only thing that beats php_admin_value[memory_limit]. Correct for a VPS or a dedicated box, and the only answer when the runtime flag above says the value is fixed.
  • .htaccess: works only under mod_php, which most modern hosts no longer run. See below.

Why an .htaccess php_value line is usually ignored

The snippet people paste into .htaccess looks like this:

# .htaccess — only has an effect when PHP runs as an Apache module.
<IfModule mod_php.c>
	php_value memory_limit 512M
</IfModule>

Under mod_php, with AllowOverride Options enabled, that works. Under PHP-FPM, which is what nearly every host runs now, Apache never sees a PHP directive and the block is a no-op: the limit does not move and you conclude that raising memory simply does not work. Worse, an unguarded php_value line under mod_proxy_fcgi produces Invalid command ‘php_value’ and a 500 on every request. If you cannot confirm mod_php is loaded, skip this route entirely; a silent no-op is harder to debug than an error.

Raise the limit in wp-config.php the way WordPress expects

Add two constants above the line that requires wp-settings.php:

/**
 * Memory ceiling for WordPress requests.
 * Must sit above the line that requires wp-settings.php.
 */
define( 'WP_MEMORY_LIMIT', '256M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );

WP_MEMORY_LIMIT is the target for ordinary front-end requests. WP_MAX_MEMORY_LIMIT is what wp_raise_memory_limit() applies in admin, AJAX, cron and image-editing contexts, so a 256M front end with a 512M admin is a sane split: the block editor, plugin updates and thumbnail regeneration are the requests that actually need the headroom.

WordPress only raises the limit, never lowers it, so a constant below the server value does nothing. Do not reach for ini_set( 'memory_limit', '-1' ) here: unlimited memory on a shared box turns a clean fatal into a slow death by swapping, and you lose the one signal that told you something was wrong. If the diagnostic above reported the value as fixed, this block will be ignored: go to the server-side route instead.

Push the ceiling from the server side with .user.ini or php.ini

Create .user.ini in the WordPress root, or edit the matching lines in the loaded php.ini:

; .user.ini in the WordPress root, or the matching lines in php.ini
memory_limit = 512M
max_execution_time = 120

Two details trip people up. First, .user.ini is only read when user_ini.filename is set (it is by default) and PHP runs as FPM or FastCGI; under mod_php the file is ignored. Second, the values are cached, so after saving, wait out user_ini.cache_ttl or reload PHP-FPM before you re-run the diagnostic. If the value still refuses to move, the pool config has php_admin_value[memory_limit] set, and no file inside the site can override it: that is a support ticket, not a code change.

Remember that WP-CLI uses the CLI php.ini, which often has a different (sometimes unlimited) limit from the web server. A wp command succeeding proves nothing about a browser request.

Rank plugins by peak memory with WP-CLI before you blame one

Guessing which plugin is heavy is unreliable, and deactivating them one at a time on a live site is worse. WP-CLI can load WordPress with a chosen subset of plugins, so you can measure each one’s bootstrap cost in isolation:

#!/bin/bash
# Peak memory per active plugin: load one plugin at a time, skip the rest.
all=$(wp plugin list --status=active --field=name | paste -sd, -)

printf '%-34s %s\n' 'plugin' 'peak MB'
printf '%-34s %s\n' '(core only)' "$(wp --skip-plugins eval 'echo round(memory_get_peak_usage(true)/1048576,1);')"

for plugin in $(wp plugin list --status=active --field=name); do
	skip=$(printf '%s\n' "$all" | tr ',' '\n' | grep -vx "$plugin" | paste -sd, -)
	if [ -z "$skip" ]; then
		peak=$(wp eval 'echo round(memory_get_peak_usage(true)/1048576,1);')
	else
		peak=$(wp --skip-plugins="$skip" eval 'echo round(memory_get_peak_usage(true)/1048576,1);')
	fi
	printf '%-34s %s\n' "$plugin" "$peak"
done

The first row is the baseline: WordPress with every plugin skipped. Each following row loads exactly one plugin, so the difference from the baseline is what that plugin costs before it does anything useful. memory_get_peak_usage( true ) is the number that matters: current usage tells you where you are now, peak tells you what nearly killed the request.

This measures the bootstrap only. A plugin that allocates nothing at load time and then builds a 300 MB table on wp_ajax_export or a nightly cron event will look innocent here, which is why the next step exists.

Catch the plugin that dies mid-request with a shutdown-hook logger

Drop this in wp-content/mu-plugins/memory-watch.php. Must-use plugins load before regular plugins, so the logger is already watching when the guilty plugin runs:

<?php
/**
 * Plugin Name: Memory Watch
 * Description: Logs peak memory per plugin and the request that runs out of it.
 * Version:     1.0.0
 */

defined( 'ABSPATH' ) || exit;

define( 'MEMORY_WATCH_LOG', WP_CONTENT_DIR . '/memory-watch.log' );
define( 'MEMORY_WATCH_RATIO', 0.8 ); // Log once a request passes 80% of the limit.

$GLOBALS['memory_watch_marks'] = array();

/**
 * Memory in use right after each plugin file has been included.
 *
 * @param string $plugin Absolute path to the plugin file.
 */
function memory_watch_mark( $plugin ) {
	$GLOBALS['memory_watch_marks'][ $plugin ] = memory_get_usage( true );
}
add_action( 'plugin_loaded', 'memory_watch_mark' );

/**
 * Build the log entry for the current request.
 *
 * @param string $note Optional extra line, such as the fatal error message.
 * @return string
 */
function memory_watch_report( $note = '' ) {
	$request = isset( $_SERVER['REQUEST_URI'] ) ? esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : 'cli';
	$lines   = array(
		sprintf( '--- %s  %s', gmdate( 'Y-m-d H:i:s' ), $request ),
		sprintf( 'peak %s of %s', size_format( memory_get_peak_usage( true ) ), ini_get( 'memory_limit' ) ),
	);

	if ( '' !== $note ) {
		$lines[] = 'fatal: ' . $note;
	}

	$deltas   = array();
	$previous = 0;

	foreach ( $GLOBALS['memory_watch_marks'] as $plugin => $bytes ) {
		$deltas[ $plugin ] = $bytes - $previous;
		$previous          = $bytes;
	}

	arsort( $deltas );

	foreach ( array_slice( $deltas, 0, 5, true ) as $plugin => $bytes ) {
		$lines[] = sprintf( '  +%s  %s', size_format( $bytes ), plugin_basename( $plugin ) );
	}

	return implode( "\n", $lines ) . "\n";
}

/**
 * Write the entry once per request.
 *
 * @param string $note Optional extra line.
 */
function memory_watch_write( $note = '' ) {
	static $done = false;

	if ( $done ) {
		return;
	}

	$done = true;
	error_log( memory_watch_report( $note ), 3, MEMORY_WATCH_LOG );
}

/**
 * Normal requests: log only when the peak got close to the ceiling.
 */
function memory_watch_shutdown() {
	$limit = wp_convert_hr_to_bytes( ini_get( 'memory_limit' ) );

	if ( $limit > 0 && memory_get_peak_usage( true ) < $limit * MEMORY_WATCH_RATIO ) {
		return;
	}

	memory_watch_write();
}
add_action( 'shutdown', 'memory_watch_shutdown', 0 );
register_shutdown_function( 'memory_watch_shutdown' );

/**
 * Hard fatals: WordPress applies this filter just before it renders the error page.
 *
 * @param string $message Message shown to the visitor.
 * @param array  $error   Error details from error_get_last().
 * @return string
 */
function memory_watch_fatal( $message, $error ) {
	memory_watch_write( $message );

	return $message;
}
add_filter( 'wp_php_error_message', 'memory_watch_fatal', 10, 2 );

The plugin_loaded action fires after each plugin file is included, so the marks are a timeline of the request rather than a snapshot. At the end, the deltas are sorted and the five biggest are written out with the peak and the limit.

Three write paths look like overkill until you have watched a fatal: WordPress’s own fatal handler renders the error page and ends the request, which can happen before later shutdown callbacks run. The shutdown action and the raw shutdown function cover ordinary requests that get close to the ceiling; the wp_php_error_message filter fires inside the fatal handler, just before the error page is printed, and that is the path that survives a hard fatal. A static guard keeps it to one entry per request.

Keep the log out of reach: wp-content is web-accessible, so either point MEMORY_WATCH_LOG at a path above the document root or add a deny rule for memory-watch.log. Delete the mu-plugin once you have your answer: it is a diagnostic, not a permanent feature.

The critical error page a visitor sees when the request runs out of memory (test site: WordPress 7.1.3, PHP 8.2, WooCommerce 11.2.2)
The critical error page a visitor sees when the request runs out of memory (test site: WordPress 7.1.3, PHP 8.2, WooCommerce 11.2.2)

The logger’s entry: peak memory, the fatal message and the plugins that grew the request (test site: WordPress 7.1.3, PHP 8.2, WooCommerce 11.2.2):

--- 2026-11-11 01:46:45  
peak 124 MB of -1
  +67 MB  woocommerce/woocommerce.php
--- 2026-11-11 01:46:49  
peak 124 MB of -1
  +67 MB  woocommerce/woocommerce.php

What to change once the log names a plugin

With a name and a number, the fix is usually obvious:

  • One plugin dominates the timeline. Update it first; memory leaks in page builders and import tools are routinely fixed in minor releases. If the current version is the problem, look for a lighter alternative rather than raising the limit again.
  • The peak is in admin or cron only. Leave WP_MEMORY_LIMIT alone and raise WP_MAX_MEMORY_LIMIT. Then break the cron job into batches: wp cron event run <hook> for a single event is a quick way to reproduce it.
  • Nothing stands out and the peak is still high. The cost is in the query, not the plugin: posts_per_page => -1, an unbounded meta_query, or a page builder loading every revision. Fix the query before you buy more memory.

The same php.ini and .user.ini precedence decides your upload limit too, which is covered in increasing the WordPress max upload file size. If image uploads fail with a generic “HTTP error” rather than a memory fatal, start with fixing the HTTP error when uploading images.

Once the fatal is gone, the same measurement habit is worth pointing at the database: autoloaded options are loaded on every single request, and a handful of leftover plugin settings can quietly add megabytes before any plugin runs. wp option list --autoload=on --orderby=size --order=desc --fields=option_name,size prints them largest first, and anything left behind by a plugin you deleted is safe to remove.

Share this:

  • Share on X (Opens in new window) X
  • Share on Facebook (Opens in new window) Facebook
  • Share on LinkedIn (Opens in new window) LinkedIn
  • Share on WhatsApp (Opens in new window) WhatsApp
  • Share on Reddit (Opens in new window) Reddit
  • Email a link to a friend (Opens in new window) Email

Related

Advertisement
Previous Article Add Custom Fields to WooCommerce Checkout

About the author

Md. Zubaer Ahammed

Md. Zubaer Ahammed

Md. Zubaer Ahammed is a senior full-stack developer building learning platforms and modern web systems with WordPress, Laravel, Python/Django, Vue, and React. More at https://zubaer.com/.

I also build WordPress plugins, including ZubFeat AI Featured Image and ZubQuant. See my plugins and services →

Related Posts

  • Fix WordPress Database Connection Error Fix WordPress Database Connection Error
  • Secure WordPress site from hacking, DDoS and Brute force attack How to Secure WordPress Site From Hacking, DDoS and Brute Force Attack
WP Tuts Hub

WordPress tutorials, themes, and plugins — written for builders.

Topics

  • WordPress & AI
  • WordPress Security
  • WordPress Development
  • WordPress Troubleshooting
  • WordPress Tips and Tricks

Resources

  • My Plugins
  • Portfolio
  • About WP Tuts Hub
  • Contact Me

© 2026 WP Tuts Hub · Md. Zubaer Ahammed

Privacy Policy Terms of Use