Sharing some useful tips, solutions and notes for Geeks.

Friday, July 14, 2017

Allowed memory size exausted error in Admin of Wordpress

Recently i met with an issue in Wordpress Admin regarding the memory size getting exhausted for the custom post type listing page(all posts page). That custom post type stores large data and whenever the page is taken, it says 500 internal server error.

So to troubleshoot, first i enabled the log in wp-config.php file resides in the document root of the Wordpress.

To enable, just change/add this:

define('WP_DEBUG', true);

After that i could easily see what was the error that occurring behind the seen. I found the memory the size got exhausted. The error was like this:

"Fatal error: Allowed memory size of **** bytes exhausted (tried to allocate 64 bytes) in /xxx/wp-includes/wp-db.php on line ****"

To fix the issue, just put below code in functions.php file of your theme folder. Replace userquote with your custom post type.


       
function sk_pre_get_posts( WP_Query $wp_query ) {

if ( in_array( $wp_query->get( 'post_type' ), array( 'userquote' ) ) ) {

$wp_query->set( 'update_post_meta_cache', false );

}

}




// Only do this for admin

if ( is_admin() ) {

add_action( 'pre_get_posts', 'sk_pre_get_posts' );

}

After this refresh the page again, Voila the error is gone!!!!


Why? Because Wordpress tends to preload postmeta of all posts when we takes all posts page. So to override this, above code will ask Wordpress not to load.

Any queries let me know. :)










No comments: