Created
September 6, 2017 14:47
-
-
Save morgyface/14bb9bd9d3207d3039f0e5a7ffd3b404 to your computer and use it in GitHub Desktop.
WordPress | Get Posts Odd or Even
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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(); | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.