I’m new to WordPress development and recently found myself needing to create a secondary query using WP_Query. The Codex has a pretty good introduction to querying WordPress using WP_Query but no where, not even in the new Developer documentation, do they say that you MUST call the_post()
inside the loop. If you fail to call the_post()
, you may get the error “Fatal error: Maximum function nesting level of ‘100’ reached, aborting!”
To the documentation team’s credit, they do point out that if you fail to call the_post()
, many template tags will fail to function as expected. Also, in a few places they do mention that the_post()
increments the internal counter by one. It makes me wonder why have_posts()
doesn’t just call the_post()
internally and be done with it…
I lost hours trying to figure this out. And just for the sake of completeness, here is a full example of what WordPress needs to properly execute a loop as a secondary query (and it matters not that this is against a custom post type):
$my_query = new WP_Query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post(); // does nothing visual, just sets some variables and advances the internal pointer
the_title(); // note that we do NOT use $my_query->the_title(), I have no idea why not…
}
wp_reset_postdata(); // reset the main post variable, $wp_the_post to the main query
And it should be noted that all those posts about the problem being XDebug are all just wrong. The problem is not the limit placed on the number of nested function calls (100 seems far, far more than adequate) but the fact that you’ve reach 100 in the first place.
I sincerely hope this helps others in the same situation.