Using PHP to control dynamic content

First here’s a bit better explanation of the title – How to control your dynamic output (posts, navigation, feeds…) with simple use of PHP, of course this can be used where every you have automatically created content, but since we develop themes here, we’ll stick to WordPress!

To demonstrate this i’ll be using 3 very common problems that you have probably ran into while developing themes, all of them are about main posts loop, but as i said you can use it where ever you want!

First problem, making the latest post different style
Idea is to put a counter into the main WordPress loop and simply tell on what ID (post) you want to apply another (or different) class. Like we used for Andromeda Theme

featuredpost

<?php $i=1; ?>
 
<?php while (have_posts()) : the_post(); ?>      
 
      <div id="post-<?php the_ID(); ?>" class="post <?php if ($i == 1) { echo ‘alt’; } ?>">
           post content
      </div>  
 
     <?php $i++; ?>

<?php endwhile; ?>
 

Second problem, repeating blocks can’t fit wrapper width because of last padding
This is like the most typical thing, you can see it everywhere and if you’re not CSS expert (because it can be fixed with CSS) let’s apply style without padding to the latest horizontal block in the row, call it last (and of course you have to define it in CSS like .last { padding:0px; } or something.

paddingright

<?php $i=1; ?>
 
<?php while (have_posts()) : the_post(); ?>      
 
      <div id="post-<?php the_ID(); ?>" class="post <?php if( $i % 3 == 0 ) echo ‘ last’; ?>">
           post content
      </div>  
 
     <?php $i++; ?>

<?php endwhile; ?>
 

So you see, similar thing here, just we’re checking if module is == 0, so you can have this in every row for 3 posts not just for the first one

Third problem, different box heights breaking the layout
Here’s the situation, you have posts sorted like in previous example, so horizontal boxes in multiple lines but when they are different heights they most often don’t go in right order, so what we’re about to do is to put some clear both after every line. We’ve used this in our Gemini Theme

heights

<?php $i=1; ?>
 
<?php while (have_posts()) : the_post(); ?>      
 
      <div id="post-<?php the_ID(); ?>">
           post content …
      </div>  
     
     <?php if (($i%3) == 0) { echo "<div style=’clear:both;’></div>"; } ?>

     <?php $i++; ?>

<?php endwhile; ?>
 

Posted by: ThemeGalaxy on April 4, 2009
Easy To Customize

Theme Galaxy's WordPress themes are easy to understand and to edit within the WordPress Administration panel, allowing you to flexibly customize your theme.

Save CPU + Memory

Website templates from Theme Galaxy have been built lightly, incorporating optimized code, to help you save substantial CPU + memory usage on your server.

Up-To-Date WordPress

Our cutting-edge premium WordPress themes are compatible with recent and legacy WordPress releases.