Tuesday, August 23, 2011

Show all blog posts on multiple static pages in WordPress

I am working on a hybrid blog/website project using Wordpress and I had a special request come in from one of my clients; He wanted his home page to be a static page, which is easy to do, but instead of having another page as the blog posts page he wanted two blog posts pages. The sidebar would be different for these pages, but the posts would be the same. His reason for this made sense, so I went about looking for a good way to implement it. Using the Reading settings you can only set one page as the posts page. Plus, I wanted to be able to specify a different layout (really just the sidebar is different) for each page, so I couldn't use the Reading settings for this.

The way I addressed this was to create two Pages. I created the layouts for each page with my iThemes Builder Style Manager plugin. Then I created a new page template, so that the pages would display posts instead of the page content. I took my theme's single.php code and expanded it so that it would show all of the posts plus the static Page's title at the top. I copied the loop code from my theme's single.php file. Below you can see the part that I changed, which is just the top part of the file:
<?php
/**
 * Template Name: Posts Page
 *
 * A custom page template for DataPoints
 *
 */
function render_content() {
?>

<!-- Display the page title -->

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
 <div class="post">
  <!-- Display the Title as a link to the Post's permalink. -->
  <h1><?php the_title(); ?></h1>
  <hr/>
 </div>
<?php endwhile; endif; ?>

<!-- Show all of the blog posts -->
<?php query_posts( 'posts_per_page=5' ); ?>
<?php if ( have_posts() ) : ?>
  <div class="loop">
   <?php while ( have_posts() ) : // The Loop ?>
    <div class="loop-content">
     <?php the_post(); ?>
<!-- The rest of this is identical to my theme's single.php file -->
...[SNIP]...