'Second loop on Wordpress page not working
Disclaimer: I am trying to help someone with adding another section to their Wordpress site. I did not write most of this code.
I am using a different custom post type for each WP_Query loop. Both loops work fine on their own, but when I try to run them on the same page, the second one doesn't show any posts.
Things I have tried:
- wp_reset_query();
- wp_reset_postdata();
- changing the names of $query and $args so each is unique
- moving the reset function to inside if() (but still outside the while loop)
I have looked at every post I can find on the subject and tried all the suggestions, but nothing is working. Surely I am missing something.. Maybe another set of eyes can help me find the problem. I have posted the relevant code below.
/* ---- First Loop ---- */
<?php
$args = array(
'post_type' => 'casestudies',
'post_status' => 'publish',
'order' => 'ASC',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
/* ---- Do Stuff ---- */
endwhile;
endif;
wp_reset_query();
?>
/* ---- Second Loop ---- */
<?php
$args = array(
'post_type' => 'whitepages',
'post_status' => 'publish',
'order' => 'ASC',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) :
$query->the_post();
/* ---- Do Stuff ---- */
endwhile;
endif;
wp_reset_query();
?>
Edit:
I found the solution with help from the accepted answer. I posted what I did to fix everything in another answer below.
Solution 1:[1]
I found a solution! It was not, in fact, the WP_Query() loops causing the issue, but the carousels holding the posts being displayed. Each loop places custom posts into a carousel, and I was re-using the same id for each of the carousels on the page. This did not play nice with the JavaScript.
To correct this, I made a copy of the JavaScript function in the main js file, but changed the #original-name to #other-name. I also changed carousel id to other-name.
Everything now works as intended. Thank you @tomekpryjma for helping me confirm that my loops looked good so that I could stop fixating on that being the issue.
Solution 2:[2]
Using <?php wp_reset_postdata(); ?> after while loop solved the problem.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Akashxolotl |
