Forums

Styling odd and even numbered posts differently (3 posts)

  1. Anonymous
    Unregistered
    Posted 1 year ago #

    Say I want to style posts with a different background color depending on whether they're odd or even. I'm thinking, in terms of pseudo-code, something like this:

    if ((post-id % 2) == 0)
        <div class="even">
    else
        <div class="odd">

    But how do I do this in a PHP Wordpress template?

  2. nickyeung
    Member
    Posted 8 months ago #

  3. greenshady
    Member
    Posted 8 months ago #

    Every theme will be different, so I'll make the assumption that your theme has something like this:

    <div class="post">

    First, you'd replace that with this:

    <div class="post <?php my_post_class(); ?>">

    Then, add this PHP to your functions.php file:

    function my_post_class() {
    	global $post_num;
    
    	if ( ++$post_num % 2 )
    		$class = 'even';
    	else
    		$class = 'odd';
    
    	echo $class;
    }

    There are several methods to use now though because WP has its new post_class().

Topic Closed

This topic has been closed to new replies.

About this Topic