Wednesday, May 20, 2009

Wordpress: Excerpts and Random Posts, And How to alternate background colors

As I've said on my last blog I'm going to create an excerpts section, whilst working on my perfect basic wordpress theme, I made this code.
<?php if (have_posts()) : $odd = true ?>

<?php

//displays post from the latest to the oldest

//$rand_posts = get_posts('numberposts=5&order=DSC');

//displays post from the oldest to the latest

//$rand_posts = get_posts('numberposts=5&order=ASC');

//displays random posts

$rand_posts = get_posts('numberposts=5&orderby=rand');

foreach( $rand_posts as $post ) :

?>



<div class="entry <?php if ($odd) echo ' odd'; ?>">

<h3><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></h3>

<?php the_excerpt();?>

</div>

<?php

$odd = !$odd;//ends the odd post test

?>

<?php endforeach; ?>

<?php endif; ?>
Okay so its not really original you can find similar codes in wordpress support forums but I need this blog to document my own work. Now lets look at this more closely:
<?php if (have_posts()) : $odd = true ?>
Just like any standard wordpress theme you'll see the familiar if... have_posts... stuff, what I've added here is the string odd with a boolean value of true. What it does is identify if the post has an id value equivalent to an odd number. Moving on to the next line rather lets jump to this line of code:
<div class="entry <?php if ($odd) echo ' odd'; ?>">
.
.
.
$odd = !$odd;
.
.
.
This line simply adds the class odd if the value of the $odd above is an odd number, I had to jump like this to keep my train of thought and perhaps yours. Okay jumping again to the last code above, this simply ends the odd thingy above(making the $odd value to false), otherwise Wordpress will add all with an extra odd class.

Now going back up a line or two:
.
.
.
$rand_posts = get_posts('numberposts=5&orderby=rand');

foreach( $rand_posts as $post ) :
.
.
.
Yeah, this is what it looks like, it displays 5 posts randomly, and that is it.

For further reference try these links:

http://codex.wordpress.org/Template_Tags/get_posts#Random_posts
http://codex.wordpress.org/Template_Tags/query_posts

No comments:

Post a Comment