Skip to content

Instantly share code, notes, and snippets.

@morgyface
Created September 6, 2017 14:47
Show Gist options
  • Select an option

  • Save morgyface/14bb9bd9d3207d3039f0e5a7ffd3b404 to your computer and use it in GitHub Desktop.

Select an option

Save morgyface/14bb9bd9d3207d3039f0e5a7ffd3b404 to your computer and use it in GitHub Desktop.
WordPress | Get Posts Odd or Even
<?php
$args = array(
'posts_per_page' => 5,
'post_type' => 'post'
);
$posts = get_posts( $args );
if ( $posts ) {
$counter = 1;
echo '<ul>';
foreach ( $posts as $post ) : setup_postdata( $post );
$post_title = get_the_title();
echo '<li class="';
if( $counter % 2 == 0 ) { // We use modulo to work out if there is a remainder when the counter is divided by 2.
echo 'even';
} else {
echo 'odd';
}
echo '">';
echo '<h2>' . $post_title . '</h2>';
echo '</li>';
$counter++;
endforeach;
echo '</ul>';
}
wp_reset_postdata();
?>
@morgyface
Copy link
Copy Markdown
Author

morgyface commented Sep 6, 2017

Odd or even get_posts

I was developing a site where content position varied from post to post depending on whether it was odd or even, so it wasn't something that could be solved using a CSS3 nth-child selector. This gist uses the Arithmetic Operator Modulo which converts its operands to integers before calculating a remainder. So by dividing by 2 we would expect no remainder on even values. Essentially it becomes an odd/even test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment