This page looks best with JavaScript enabled

how to display post from different post types on the same page

 ·  ☕ 2 min read  ·  👽 john hashim

In this simple post, we will be looking How to show posts from multiple post types in a single loop? And display them separately on the same template.

ever wonder how news sites, e-commerce, and blog sites manage to display different article section on the same page.

to get started you will create your main function in a function.php. you can copy this code and modify it in your way

1
2
3
4
5
6
7
8
<?php
function joh_get_posts_by_type( $post_type, $num_posts ) {
 return get_posts( array(
  'posts_per_page'   => $num_posts,
  'post_type'        => $post_type,
 ));
}
?>

now this function will query post types and the number of posts to be displayed per section.

now you need to call your custom post type you created earlier on your custom template for example homepage.php …

1
2
3
4
5
6
7
8
<?php
$developent = joh_get_posts_by_type( 'development', 3 );
$portifolio = joh_get_posts_by_type( 'portifolio', 3 );
$guides = joh_get_posts_by_type( 'guides', 3 );
$ebooks = ds_joh_posts_by_type( 'ebook', 3 );
$testimonials = joh_get_posts_by_type( 'testimonials', 3 );
//post_type = our funtions that we created earlier  ( 'post type slug', number of post 0);
?>

then to display your post you will need to create a loop to call all post from a given templates

like:

1
2
3
4
5
6
7
<?php
foreach ( $portifolio as $post ) :
setup_postdata( $post );
get_template_part( 'template-parts/content', get_post_format() );//or the name of your tamplate you want to show 
endforeach;
wp_reset_postdata();
?>

OR

1
2
3
4
5
6
7
8
9
<?php
foreach ( $blog as $post ) :
setup_postdata( $post );
   the_post_thumbnail($size);
   the_title();
   the_content();
endforeach;
wp_reset_postdata();
?>

if your using ACF fields to display certain post this might be the options increase if you want to display recent post or popular post was you

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
  $recent_posts = ( get_field( 'field_name') ? get_field( 'field_name' ) : get_field( 'field name', 'options' ) );
  ?>
  <?php if ( $recent_posts ) : ?>
   <?php foreach ( $recent_posts as $post ) : ?>
    <?php setup_postdata( $post ); ?>
      //  do some magic here 
   <?php endforeach; ?>
    <?php wp_reset_postdata(); ?>
  <?php endif; ?>
Share on

john hashim
WRITTEN BY
john hashim
Web Developer