How to Increase the Memory Limit in WordPress

WPTurbo » Snippets » How to Increase the Memory Limit in WordPress
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Is your WordPress website running out of memory? Have you ever encountered a message saying "Fatal error: Allowed memory size of xxxxx bytes exhausted"? If so, your site might benefit from increasing its PHP memory limit. In this article, we will guide you through the steps to safely increase the memory limit in WordPress, enhancing your website’s performance and stability. Don’t worry, no advanced technical knowledge is required – we’ll walk you through the process in a simple, easy-to-understand way.

					define('WP_MEMORY_LIMIT', '256M');

function wpturbo_increase_memory_limit() {
    if (WP_MEMORY_LIMIT < '256M') {
        ini_set('memory_limit', '256M');
    }
}
add_action('init', 'wpturbo_increase_memory_limit');
				

The code snippet begins with a PHP constant called WP_MEMORY_LIMIT which is set to '256M'. This constant is used in the WordPress core to set the maximum amount of memory that can be consumed by PHP. The value of 256M is a common setting and should be adequate for most WordPress websites.

define('WP_MEMORY_LIMIT', '256M');

The second part of the snippet declares a function named wpturbo_increase_memory_limit().

function wpturbo_increase_memory_limit() {
    if (WP_MEMORY_LIMIT < '256M') {
        ini_set('memory_limit', '256M');
    }
}

The function checks if the WP_MEMORY_LIMIT is set to a value less than 256 Megabytes. If it is, the function sets the PHP memory_limit value to 256 Megabytes by using the PHP function ini_set().

The ini_set() function requires two versions - the name of the setting to alter, and the value to which it is to be set. The memory_limit can be set at runtime, but the setting only affects the script it is used in. The original system-wide setting is not changed.

Finally, we hook our wpturbo_increase_memory_limit() function to the init action hook.

add_action('init', 'wpturbo_increase_memory_limit');

The init action hook is one of the many hooks provided by WordPress and is typically used for things that should happen after WordPress finishes loading but before any headers are sent. By hooking our function to initialize action, we ensure that our custom memory limit setting function is fired off whenever WordPress runs, but before any headers are sent out. This lets us increase the memory limit for WordPress operations without affecting the rest of the server.

In summary, this snippet helps in increasing the PHP memory limit for WordPress to ensure that your WordPress operations have sufficient memory to perform their tasks optimally.

Register an account to save your snippets or go Pro to get more features.