Contact Us

When a WordPress site shows an error like:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 2359296 bytes) in /path/to/file.php on line 123

… it’s a frustrating indicator that your site ran out of PHP memory. This can break your site, prevent plugin activation, or crash pages. But don’t worry — it’s one of the most common WordPress errors, and with proper fixes you can resolve it safely.

In this guide, we’ll cover:

  • What the “Allowed Memory Size Exhausted” error means

  • Why it happens (root causes)

  • How to fix it step-by-step (safe methods)

  • Best practices to prevent running out of memory

  • Code snippets for all major fix methods

  • Advanced techniques (performance, monitoring)

  • FAQs and tips for various hosting setups

By the end, you’ll be able to eliminate this error permanently and keep your WordPress site stable.

What Does “Allowed Memory Size Exhausted” Mean?

When PHP scripts run, they consume memory to execute code. PHP has a memory limit (configured in php.ini or by the host). When your script tries to use more memory than that allowed limit, PHP throws this fatal error meaning it attempted to allocate memory beyond what’s permitted.

Example error message:

Fatal error: Allowed memory size of 67108864 bytes exhausted (tried to allocate 2359296 bytes) in /wp-includes/class-wp-query.php on line 123

Here, 67,108,864 bytes = 64MB was the allowed memory, and it tried to allocate ~2.3MB more. That caused the crash.

This error can occur:

  • On the admin side (activating a plugin)

  • On the public side (loading a heavy page)

  • During backups, imports, or complex queries

  • When scripts or plugins go into infinite loops or heavy recursion

Why Does It Happen? (Root Causes)

Before applying fixes, it’s essential to understand what’s causing the memory exhaustion in your site. Here are the typical culprits:

  1. Too low PHP memory limit
    Many shared hosts set a low limit like 32M or 64M — insufficient for modern WordPress.

  2. Memory-hungry plugins or themes
    A plugin that makes many database calls or loads heavy libraries can consume memory quickly.

  3. Large loops / recursive functions
    Custom code or flawed loops (e.g. infinite loops) that accumulate data.

  4. Large imports / backups / database operations
    When handling large sets of data, the script might hit memory caps.

  5. Poorly coded theme or query
    Very heavy WP_Query or custom loops that pull too many records.

  6. Memory leaks in code
    Not releasing references, keeping large arrays, or caching huge objects.

  7. Concurrent processes or CRON
    Multiple processes at once may collectively exhaust memory.

How to Safely Fix the Memory Exhausted Error (Step by Step)

Below are progressive methods — start with the simplest, and only escalate if needed. Always take backups before making changes.

Method 1: Increase PHP Memory Limit

The simplest fix often works: bump up the memory limit.

Via wp-config.php

Add this just above the line /* That’s all, stop editing! */:

define( 'WP_MEMORY_LIMIT', '256M' );
define( 'WP_MAX_MEMORY_LIMIT', '512M' );
  • WP_MEMORY_LIMIT controls front-end memory limit

  • WP_MAX_MEMORY_LIMIT is used in admin tasks (e.g. updates, plugin activation)

For example:

if ( ! defined( 'WP_MEMORY_LIMIT' ) ) {
define( 'WP_MEMORY_LIMIT', '256M' );
}
if ( ! defined( 'WP_MAX_MEMORY_LIMIT' ) ) {
define( 'WP_MAX_MEMORY_LIMIT', '512M' );
}

Via php.ini

If you control your server’s php.ini, find:

memory_limit = 128M

and increase to:

memory_limit = 256M

Then restart your web server (Apache / Nginx / PHP-FPM).

Via .htaccess (Apache)

php_value memory_limit 256M

⚠️ Some hosts disable php_value in .htaccess. If it causes internal server error, remove it.

Via hosting dashboard or control panel

On many managed hosts (cPanel, Plesk, etc.), you can adjust PHP memory from UI. Look for PHP settings or Select PHP Version tool.

Method 2: Disable or Replace Memory-Heavy Plugins

If increasing memory still doesn’t fix the issue, the problem might be a plugin or theme.

  • Deactivate all plugins temporarily, and reactivate one by one to find the culprit.

  • Use Query Monitor plugin to identify which plugin or query is consuming memory.

  • If a specific plugin is heavy, consider replacing it with a lightweight alternative.

Example:

If plugin-heavy-gallery causes memory errors, deactivate it and try Foo Gallery or other efficient gallery plugin.

Method 3: Optimize Theme / Custom Code

If you have custom code or heavy loops:

  • Use pagination in loops instead of pulling all posts

  • Avoid get_posts() with very large limits; use smaller batches

  • Free memory by unsetting large variables when done:

$rows = $wpdb->get_results( $sql );
foreach ( $rows as $row ) {
// process
}
unset( $rows );
  • Avoid nested loops or over-aggregating data

Method 4: Offload Heavy Processes (Tools, Imports)

Large tasks like imports or backup scripts should run in batches or via WP-CLI, not via web requests.

Example: When importing 10,000 posts, break into chunks of 100 posts.

Use WP_CLI commands instead of doing imports through admin screens where memory is limited.

Method 5: Use Object Caching / Transients Wisely

Use a drop-in cache (Redis, Memcached) to store expensive data and avoid running the heavy query repeatedly.

Also, clear expired transients:

global $wpdb;
$wpdb->query(
"DELETE FROM {$wpdb->options} WHERE option_name LIKE '\_transient\_%' AND option_name NOT LIKE '\_transient\_timeout\_%'"
);

Method 6: Monitor Memory Usage Real-Time

Insert debug code in wp-config.php (temporarily) to monitor:

add_action( 'shutdown', function() {
if ( function_exists( 'memory_get_peak_usage' ) ) {
error_log( 'Peak memory usage: ' . round( memory_get_peak_usage( true ) / 1048576, 2 ) . ' MB' );
}
});

That logs to wp-content/debug.log how much memory was used before crashing (if it still does).

Example Scenario & Code Fix Walkthrough

Let’s imagine this error:

Allowed memory of 67108864 bytes exhausted in class-wp-query.php on line 567

Diagnosis:

  • It means WP_Query tried to handle too many posts or data.

  • A plugin or theme might be doing new WP_Query(['posts_per_page' => 9999]).

Fix:

  1. Change the query to use pagination or smaller limits:

    $args = [
    'posts_per_page' => 100,
    'paged' => get_query_var( 'paged', 1 ),
    'post_status' => 'publish',
    ];
    $the_query = new WP_Query( $args );
  2. If this is in a plugin’s admin import, break into batches:

    $batch_size = 200;
    // assume $total is the full count
    for ( $offset = 0; $offset < $total; $offset += $batch_size ) {
    $args['posts_per_page'] = $batch_size;
    $args['offset'] = $offset;
    $batch = new WP_Query( $args );
    // process, then unset
    unset( $batch );
    }
  3. If still not enough memory, combine with increasing WP_MEMORY_LIMIT.

Best Practices to Prevent Running Out of Memory

  • Keep memory usage lean: don’t load unnecessary libraries.

  • Use lazy-loading and on-demand loading.

  • Limit plugin count and choose efficient ones.

  • Regularly remove inactive plugins and themes.

  • Profile occasionally with Query Monitor or New Relic.

  • Avoid huge imports and process in background or via CLI.

  • Use object caching (Redis, Memcached).

  • Ensure hosting supports adequate memory (256M+).

Troubleshooting by Host Environment

Different hosts have different constraints. Here’s advice per environment:

Shared Hosting

  • Often memory is capped (64M or 128M).

  • Use minimal plugins, optimize database.

  • If error persists after maxing memory, ask host to raise memory.

Managed WordPress Hosting & VPS

  • You often control php.ini or use SFTP to adjust.

  • 256M or higher memory is standard.

  • Use caching (object cache) and consider PHP versions 8.0+.

Local Development (MAMP, XAMPP, LocalWP)

  • Open php.ini and set memory_limit = 512M.

  • Restart your server (Apache, PHP-FPM).

Summary (TL;DR)

  1. Increase memory (wp-config.php, php.ini)

  2. Disable plugins and test to find memory hogs

  3. Optimize theme / queries

  4. Use efficient import/export practices

  5. Monitor memory with debug logging

  6. Use caching and batch processing

  7. Poke host for memory upgrade if reached limits

With these steps, you can turn the dreaded memory exhaustion error into a one-off hiccup — and keep your WordPress site running smoothly even under load.

FAQs (Frequently Asked Questions)

Q1: Is there a safe maximum memory I should set?
A: 256M or 512M is usually enough. Going beyond that (1G, etc.) may hide inefficient code, not fix it. Strive for lean code.

Q2: Can I set memory limit via plugin code?
A: Yes, you can in early hooks, but it often won’t override host/server settings. Always combine with wp-config.php or php.ini methods.

Q3: Why did it work on one host but not another?
A: Because the memory limits differ across hosts. One host might be generous, another very restrictive.

Q4: Will increasing memory slow my site?
A: No — memory allocation doesn’t slow the site. The slowness comes from inefficient code. Upgrading memory gives you breathing room to fix root causes.

Q5: Can disabling caching fix it?
A: Disabling caching won’t directly fix memory errors — the cause lies in queries or loops. But caching helps avoid repeated heavy requests.

Q6: What if error occurs only in admin (when installing plugin)?
A: Use WP_MAX_MEMORY_LIMIT to allow more memory in admin tasks. Also run plugin activation manually through CLI if possible.

Subscribe To Our Newsletter & Get Latest Updates.

Copyright @ 2025 WPThrill.com. All Rights Reserved.