Wordpress: Add Content Based on Post Count

July 1, 2009 · 63 Views · Filed Under WordPress 

A couple months ago I redesigned one of my sites to use Wordpress as a CMS. It is a site that displays small video clips with a few lines of text underneath. Everything went well with the transformation and I was happy with the way it turned out, but there was one minor problem.

The pages on the site are setup to show 15 posts per page. If there aren’t 15 posts on the page, the layout gets broken. Pages 1 & 2 are fine, but page 3 doesn’t have 15 posts yet. You can see from the screenshot below what I’m talking about.

47Movies.com - before the fix

Somehow I needed to add blank posts at the end to fill up the rest of the page. Yesterday, while looking through a Wordpress tip site, I found something that made me think it would be possible. Display a text/code only if more than X posts are published

<?php
$count_posts = wp_count_posts();
if ($count_posts->publish > 10) {
    //Your code to be displayed only if more than ten posts have been published
}
?>

That code would have worked fine, but I needed it to display a dynamic number of blank posts based on the current post count. I also needed it to only display those blank posts on page 3. It was a good starting point though.

Let me start off by saying that I am NOT a php programmer, so this may be a little messy. I knew what I wanted it to do, but I had to Google everything to see how it was done in php. After piecing everything together, I finally came up with this:

1
2
3
4
5
6
7
<?php
$page_url=$_SERVER['REQUEST_URI'];
$page_number= 'page/3';
$published_posts = wp_count_posts()->publish;
while ($published_posts < 45 && strstr($page_url, $page_number) ) { ?>
   <div class="videoitem">...</div>
<?php $published_posts = $published_posts + 1; if($published_posts == 45) break; } ?>

Line 1 – start php
Line 2 – reads the URL of the website
Line 3 – declares $page_number as “page/3″.
Line 4 – uses built in function of Wordpress to declare $published_posts
Line 5 – says that while the number of posts is less than 45 and the URL contains                ”page/3″, then display the html code below
Line 6 – the html that I want shown if Line 5 is true
Line 7 – add 1 to the post count and loop it until 45

All of the code that I created went under the normal Wordpress post loop. See below:

<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
   <div class="videoitem">...</div>
<?php endwhile; else: ?>
<?php endif; ?>
 
right here

The end result now looks like this:
47Movies.com - after the fix

If you want to see it in action, go here.

Comments

Leave a Reply