0

I got a fatal error in existing code, when I debug deeper I found that it was coming from bellow line.

get_posts( array("posts_per_page"=>-1) );

Can anyone explain why is that and how to overcome it?

Error :

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /var/www/web0/html/blog/wp-includes/wp-db.php on line 2204
1

Running a no limit query is very likely the cause of your memory issues. So you might want to change your query.

If still you need to do this way, you can use the fields option, it returns post IDs only and will save a lot of memory usage - example below:

$your_query = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'fields'         => 'ids',
    )
);
  • what if need more fields like post_title ? – Janith Chinthana Jun 17 '15 at 13:17
  • even with this , it is giving the same results – Janith Chinthana Jun 17 '15 at 13:26
  • The fields attribute doesn't change what you can return on your Query - it will just optimize to use less memory. If you're still having problems with that, you need to reduce the number of posts per page by using a pagination, otherwise your server will not be able to list all your 750 posts. – Bruno Monteiro Jun 17 '15 at 13:29
-1

If your circumstances require getting all posts, try adding 'cache_results' => false to the array of arguments. So, this.

$your_query = get_posts(
    array(
        'posts_per_page' => -1,
        'post_type'      => 'post',
        'cache_results'  => false,
    )
);

That tells WP_Query to NOT cache the results, according to this line in wp-includes/class-wp-query.php:

if ( $q['cache_results'] )
    update_post_caches($this->posts, $post_type, $q['update_post_term_cache'], $q['update_post_meta_cache']);

That caching, though it can be a big help for speed if you happen to query the same post multiple times in the same request, is a memory hog and could well be the source of the memory error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.