• clockworkjoe

    (@clockworkjoe)


    I want to format a list of posts in a loop. Odd posts will be formatted one way and even posts another way.

    I have set up an If/Else using this:

    <?php if (($wp_query->post_count) % 2) : ?>

    That doesn’t work though. How can I set a IF statement to say basically IF the post count is odd do this Else do this?

Viewing 6 replies - 1 through 6 (of 6 total)
  • esmi

    (@esmi)

    Try using:

    <?php $postnum = 0;?>
     if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php $postnum++;
    $alt = 'displayed_post' . $postnum;
    $alt .= ( $postnum % 2 ) ? '' : ' alt';
    ?>
    <div <?php post_class($alt);?>>
    Thread Starter clockworkjoe

    (@clockworkjoe)

    I’m sorry but I don’t understand php well enough to know where odd posts are formatted and even posts are formatted.

    <?php if (($wp_query->post_count) % 2) : ?>
         <?php while (have_posts()) : the_post(); ?>
    ODD POSTS FORMATTED HERE
      <?php endwhile; ?>
    <?php else : ?>
         <?php while (have_posts()) : the_post(); ?>
    EVEN POSTS FORMATTED HERE
      <?php endwhile; ?>
    <?php endif; ?>

    I don’t see how to take your code and make it work

    Thread Starter clockworkjoe

    (@clockworkjoe)

    Can anyone help me?

    Alwyn Botha

    (@123milliseconds)

    ($wp_query->post_count) % 2

    The secret is that %

    that line means divide $wp_query->post_count by 2 and get the remainder;

    Thread Starter clockworkjoe

    (@clockworkjoe)

    I pulled that from a tutorial on php. What operation can I use to say basically “if the current post number is odd then true”?

    vtxyzzy

    (@vtxyzzy)

    The code you showed basically translates as:

    if the total number of posts is odd
       loop through all posts
          format them all as odd
       end
    else
       loop through all posts
          format them all as even
       end
    end

    The code esmi provided sets the post class based on the count of each post. So, post 1 would get a class of ‘displayed_post1’ and post 2 would get ‘displayed_post2 alt’. All of the even posts would get a class of ‘alt’.

    If I might alter the code a bit:

    <?php $postnum = 0;?>
     if (have_posts()) : while (have_posts()) : the_post(); ?>
    <?php $postnum++;
    $alt = 'displayed_post' . $postnum;
    $alt .= ( $postnum % 2 ) ? ' even_post' : ' odd_post';
    ?>
    <div <?php post_class($alt);?>>

    Now, you can use CSS of .even_post and .odd_post to set the formats.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘How to tell if a post is odd or even?’ is closed to new replies.