I have two different custom post type on my WP website, one is ‘item_a’ and another one is ‘item_b’. I want to display all posts in ‘item_a’ and ‘item_b’ using WP_Query object, but I can’t use two WP_Query objects at a time.So In this case, what should I do? Thanks to all genius who viewed this question!!!
<?php
$query = new WP_Query( array( 'post_type' => 'item_a' ) );
if ( $query->have_posts() ) : ?>
<?php endwhile; wp_reset_postdata(); ?>
<!-- show item_a posts -->
<?php else : ?>
<!-- show 404 error here -->
<p>404 error</p>
<?php endif; ?>
<?php
$query = new WP_Query( array( 'post_type' => 'item_b' ) );
if ( $query->have_posts() ) : ?>
<?php endwhile; wp_reset_postdata(); ?>
<!-- show item_b posts -->
<?php else : ?>
<!-- show 404 error here -->
<p>404 error</p>
<?php endif; ?>
1 Answer
Yes, you can use two instances of WP_Query
as long as you call the wp_reset_postdata
function, just like you did in your code.
You’re missing the while
statement and posts_per_page
for WP_Query
array argument item.
<?php
$query = new WP_Query( array( 'post_type' => 'item_a', 'posts_per_page' => -1 /** Show all **/ ) );
if ( $query->have_posts() ) : while($query->have_posts()) : $query->the_post(); ?>
<!-- show item_a posts -->
<?php the_title(); ?>
<?php endwhile; wp_reset_postdata(); ?>
<?php else : ?>
<!-- show 404 error here -->
<p>404 error</p>
<?php endif; ?>
<?php
$query = new WP_Query( array( 'post_type' => 'item_b', 'posts_per_page' => -1 /** Show all **/ ) );
if ( $query->have_posts() ) : while($query->have_posts()) : $query->the_post(); ?>
<!-- show item_b posts -->
<?php the_title(); ?>
<?php endwhile; wp_reset_postdata(); ?>
<?php else : ?>
<!-- show 404 error here -->
<p>404 error</p>
<?php endif; ?>