I'm trying to display a list of posts from a certain category that I can paginate through. Since I've read that get_posts()
doesn't support pagination but WP_Query
does, I'm using the latter.
Here's my query:
$mainPosts = new WP_Query(array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => 'main',
));
I originally has posts_per_page
set to 10, but I've set to 1. No matter what I try, I get an error similar to the following:
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 140513280 bytes) in /app/public/wp-includes/functions.php on line 3730
I understand that this would happen if I am trying to pull thousands of posts or performing some kind of very expensive query, but this category has a total of 5-6 posts. I can print_r
the returned object and see that it's only pulling the single post that I specified.
I should note that this only occurs if I try to run while ($mainPosts->have_posts()) { ... }
.
Here's the full code of what I am doing with the query:
if ($mainPosts->have_posts()) {
while ($mainPosts->have_posts()) {
$postItemImage = the_post_thumbnail_url();
$postPermalink = the_permalink();
$postTitle = the_title();
$postDay = the_date('F jS Y');
$postExcerpt = the_excerpt();
echo "<div class='row post-item'><div class='col-6 post-item-left'>
<div class='post-item-image' style='background-image:url(\"{$postItemImage}\")'></div></div>
<div class='col-6 post-item-detail'><h3>{$postTitle}</h3><div class='post-item-detail-header'>{$postDay}</div>
<div class='post-item-detail-main'>{$postExcerpt}</div><a href='{$postPermalink}'>Read more</a></div></div>";
}
}
What am I doing wrong here and how can I list the few posts using WP_Query
without having this memory allocation issue?
Edit: I've found that using a break;
seems to resolve the memory allocation issue, however this is of course undesirable if I intend to run the loop more than once.
memory_get_usage()
while all code in question is commented out and I see a usage of 4081472 bytes. Correct me if I am wrong but this implies that a while loop on an object containing a single post is taking 200+ MB of memory?