Skip to content
Advertisement

Multiple post loops in WordPress

I’ve built a site for a health practitioner with CPT of: (single-injuries.php, single-services.php, single-testimonials.php, single-partners.php)

and I have the appropriate (archive-injuries.php, archive-services, archive-testimonials, archive-partners) created with loops to display the relevant posts.

HOWEVER I now want to create a sitemap page that pulls ALL THE POSTS from ALL ARCHIVES and just displays the PAGE NAME and URL for each…

How do I loop through multiple archives, do I nest a loop for each within a loop?

Advertisement

Answer

You can use a custom query that queries all of your CPTs which you listed (put them into the post_type array), similar to this (which lists all post titles found, each linked to its full post):

<?php
$args = array(
    'post_type' => array('injuries', 'services', 'testimonials', 'partners' ),
    'post_status' => 'publish',
);
 $loop1 = new WP_Query($args);
          
if ( $loop1->have_posts() ) : while ( $loop1->have_posts() ) : $loop1->the_post(); 
    $post_title = get_the_title();
?>
  <div>
    <p><a href='<?php echo get_the_permalink(); ?>'><?php echo post_title; ?></a></p>
  </div>
<?php endwhile;  else: ?>
   <p>Nothing found</p>
<?php endif; ?>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement