Add WP_MEMORY_LIMIT to all WordPress installations cPanel

cPanel has a neat tool called wp-toolkit which helps to secure and update WordPress installations, themes, and plugins. The trouble is that wp-toolkit updates will fail with memory limit issues similar to the following

Unable to update plugin ”, details: Fatal error: Allowed memory size of 41943040 bytes exhausted (tried to allocate 8192 bytes) in

This can be fixed by creating and running a script which inserts WP_MEMORY_LIMIT into all wp-config.php files which in turn allows wp-toolkit to complete updates with failing. Create a script “insert_wp_memory_limit.sh” as follows:

nano insert_wp_memory_limit.sh

Insert the following:

#!/bin/sh

# Check if WP_MEMORY_LIMIT exists, if not then add it to wp_config.php with 512M RAM 

find /home/*/public_html/ -type f -name "wp-config.php" -exec sed -zi "/WP_MEMORY_LIMIT/!s/$/define('WP_MEMORY_LIMIT','512M');/" {} +

Give the script appropriate permissions to run:

chmod +x insert_wp_memory_limit.sh

Finally, run the script to give all WordPress installations a memory limit of 512M. This amount of RAM can be adjusted as required.

./insert_wp_memory_limit.sh

The script basically searches for WP_MEMORY_LIMIT within all wp-config.php files, and if it doesn’t find WP_MEMORY_LIMIT, then it adds define(‘WP_MEMORY_LIMIT’,’512M’); to the wp-config.php file. If WP_MEMORY_LIMIT is found in the wp-config.php file, then the script simply adds nothing to wp-config.php