2

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; ?>
2
  • Your item_a and item_b must be a custom post type.
    – Den Isahac
    Commented Feb 19, 2017 at 9:36
  • yes my 'item_a' and 'item_b' are the custom post type
    – kenphanith
    Commented Feb 19, 2017 at 9:41

1 Answer 1

2

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; ?>
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.