Site icon Anthony Carbon

get_the_ID() conflict in nested WP_Query codes

Hi guys, I have this problem during my WordPress coding journey. The `get_the_ID()` has conflict in nested `WP_Query` codes. On the first `WP_Query` loop, the ID for example is 20, then inside that loop I have another `WP_Query` (see the codes below) that makes the `WP_Query` codex more completed if you don’t code it right. The ID 20 is being override by sub `WP_Query` and if your trying to retrieve the ID 20, id does not give you the right ID instead this is giving you the ID of the sub `WP_Query` loop. Example on the first `WP_Query` loop and the ID is 20 and `WP_Query` sub loop ID is 21, the first loop ID will return ID of 21 and not 20.

But this can be fix by declaring the `$post` global before the `WP_Query` sub loop. See the codes below to explain this whole thing.

$args_1 = array(
	'post_type' => 'page',
);
$the_query = new WP_Query( $args_1 );
if ( $the_query->have_posts() ) {
	echo '<ul>';
	while ( $the_query->have_posts() ) {
		$the_query->the_post();
		global $post;
		$save_post = $post; // save the global post before executing the sub `WP_Query` sub loop
		echo '<li>' . get_the_title() . '</li>';
		$args_2 = array(
			'post_type' => 'post',
		);
		$the_query = new WP_Query( $args_2 );
		if ( $the_query->have_posts() ) {
			echo '<ul>';
			while ( $the_query->have_posts() ) {
				$the_query->the_post();
				echo '<li>' . get_the_title() . '</li>';
			}
			echo '</ul>';
			wp_reset_postdata();
		} else {
			// no posts found
		}
		$post = $save_post; // restore the global post after executing the sub `WP_Query` sub loop so the loop codex will return to normal
	}
	echo '</ul>';
	wp_reset_postdata();
} else {
	// no posts found
}

If you find this article more complicated, feel free to add your comments or contact me via email.

Exit mobile version