Add a List of Posts to a Custom Page Template
-
Hi,
I have the home page set up as a static page that uses a custom page template : home-page.php, in which I want to display a list of custom post types and a list of the latest posts.
The list of custom post types works fine as I have a custom query that I pass to $wpdb->get_results().
However, for the list of posts, get_posts() returns nothing.
Here’s the home-page.php template :
<?php /* Template name: Home Page */ get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'hero' ); ?> <?php endwhile; ?> <?php rewind_posts(); ?> <div class="content-wrapper clear"> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) { comments_template(); } ?> <?php endwhile; // end of the loop. ?> <!-- Display the list of custom post types : concert --> <div class="concert-list"> <h2>Upcoming converts</h2> <?php get_template_part( 'content', 'home_concert_list' ); ?> </div> <!-- Display the latest posts --> <div class="post-list"> <h2>Latest News</h2> <?php get_template_part( 'content', 'home_post_list' ); ?> </div> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
And this is the content-home_post_list.php that should display a list of the last 5 posts.
<?php global $post; $args = array( 'posts_per_page' => 5, 'post_type' => 'post' ); $myposts = get_posts($args); ?> <?php if ($myposts->size > 0) : ?> <?php foreach( $myposts as $post ) : setup_postdata($post); ?> <div class="listitem"> <article> <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <?php the_excerpt(); ?> </article> </div> <?php endforeach; ?> <?php else : ?> <p class="noEntries center">No news for the moment!<p> <?php endif; ?>
However $myposts is empty : get_posts($args) returns empty. Any ideas as to why ? Is it because I’m outside the main loop ? I read that adding global $post; would fix this. Or is it because the post type of the main page is a Page and so get_posts only has one page result ?
Thanks
- The topic ‘Add a List of Posts to a Custom Page Template’ is closed to new replies.