Nesting secondary loops
-
Hi folks!
In my plugin I’m running a secondary loop as follows:
function my_code() { // ... $query = new WP_Query( array( 'p' => $post_id, 'post_type' => array( 'post' ) ) ); if ( $query->have_posts() ) $query->the_post(); echo "- My post: " . get_the_ID() . "\n"; // Expected $post_id. $content = get_the_content(); echo "- My post: " . get_the_ID() . "\n"; // Expected $post_id, but I get something else. // ... wp_reset_postdata(); }//end my_code()
The problem arises when I retrieve the content of my post: there’s a third-party plugin that runs a secondary query when I get the content of my post and this messes my own query.
Here you have a Minimal Working Example:
function nelio_test_queries() { $query = new WP_Query( array( 'p' => 1, // /!\ Set an ID here. 'post_type' => array( 'post' ) ) ); if ( $query->have_posts() ) $query->the_post(); echo "- My post: " . get_the_ID() . "\n"; // Expected 1 second_plugin_does_some_stuff_via_hooks(); echo "- My post after the second plugin did some stuff: " . get_the_ID() . "\n"; // Expected 1 die(); }//end nelio_test_queries() add_action( 'wp_ajax_nelio_test_queries', 'nelio_test_queries' ); function second_plugin_does_some_stuff_via_hooks() { $query = new WP_Query( array( 'p' => 2, // /!\ Set an ID here. 'post_type' => array( 'post' ) ) ); if ( $query->have_posts() ) $query->the_post(); echo "- Related Post: " . get_the_ID() . "\n"; // Expected 2 wp_reset_postdata(); }//end second_plugin_does_some_stuff_via_hooks()
Call the example via AJAX:
jQuery.ajax({ url:ajaxurl, data:{action:'nelio_test_queries'}, success: x => console.log(x) })
and the expected result is:
- My post: 1 - Related Post: 2 - My post after the second plugin did some stuff: 1
but what you’ll get is:
- My post: 1 - Related Post: 2 - My post after the second plugin did some stuff: 2
How do I fix this? Keep in mind that I don’t know if the third-party plugin is or is not installed… Moreover, it’s not about this specific third-party plugin; any other plugin or theme that hooks into WordPress and runs whilst my secondary query is still active can mess my own code ??
Any help would be appreciated!
P.S. I know I can use
$query->reset_postdata()
, but do I really need to run it every time I call a function such asget_the_content
orget_the_title
, just to make sure that no other plugins changed the secondary query I’m running?
- The topic ‘Nesting secondary loops’ is closed to new replies.