The new WordPress 2.1 static homepage feature is awesome and finally makes WordPress a more viable contender in the greater Content Management System (CMS) fight but it has its difficulties. One of the main tricks to learn is how to access the main WordPress “Loop” in a static homepage. In my previous post, WordPress 2.1 static homepage , I mentioned the need to go about this differently and after multiple requests I decided to post a quick write-up on just how to do this.
The Problem: When you copy over your old template the WordPress PHP call to access the Loop now accesses just the loop for that particular page and not the global Loop. What this means is instead of displaying all your posts or even a few it just displays whatever you entered in the content box for your Static Homepage when you created it, following my writeup directions of course.
The Standard Loop Code:
<?php if ($posts) : foreach ($posts as $post) : start_wp(); ?>
<?php require('post.php'); ?>
<?php comments_template(); // Get wp-comments.php template ?>
<?php endforeach; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
The fix: Before the php code that uses the loop, you need to replace $posts with the global loop instead. To do that you call the WordPress get_posts(); function like so:
<?php $posts = get_posts( "numberposts=6" ); ?>
In the above code the variable “numberposts=6” tells WordPress how many posts to retrieve and populate the loop with.
You can also specify a category if you want to only display posts from a certain category say …. Homepage?? First you go to the admin section under Categories and find the ID of the category you want to display and then change the get_posts(); call to be something like:
<?php $posts = get_posts( "category=10&numberposts=6" ); ?>
Formatting: Since the homepage is a one-off part of your site you probably do not want to include the post.php file as in the normal loop above. I have removed that and the comment include in my site and replaced them with a more homepage friendly version which is below. I am using the the_excerpt(); function which displays a couple hundred characters of your post body as well as the the_title(), the_permalink(), the_time(), etc functions to build my own post display on the homepage.
<?php $posts = get_posts( "category=10&numberposts=6" ); ?> <?php if( $posts ) : ?> <?php foreach( $posts as $post ) : setup_postdata( $post ); ?> <div class="post"> <p class="post-info-home"><?php the_title(); ?></p> <div class="post-title-home"> <em><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link: <?php the_title(); ?>">READ ENTIRE POST</a></em><?php the_time('d M Y h:i a'); ?> </div> <div class="entry"> <?php the_excerpt(); ?> </div> </div> <?php endforeach; ?> <?php endif; ?>
Let me know if this helped you and if you still have more questions.