Use the built-in post counter

<?php
/**
* Use the built-in post counter
*
* Sometimes you'll want to keep track of which post you're on in a loop.
* Some people create their own $loop_counter (ex: Genesis, https://gist.github.com/4675237 ).
* There's a better way! A loop counter is built into $wp_query. Ex:
*
* global $wp_query;
* echo $wp_query->current_post
*
* Count starts at 0 (first post is 0, second post is 1 )
*/
/**
* Display ad after third post
*
* @author Bill Erickson
* @link http://www.billerickson.net/code/use-the-built-in-post-counter/
*/
function be_ad_after_third_post() {
global $wp_query;
if( 2 == $wp_query->current_post )
echo 'This is an ad!'
}
add_action( 'genesis_after_post', 'be_ad_after_third_post' );
/**
* Add class to first post
*
* @author Bill Erickson
* @link http://www.billerickson.net/code/use-the-built-in-post-counter/
*
* @param array $classes
* @return array
*/
function be_class_on_first_post( $classes ) {
global $wp_query;
if( 0 == $wp_query->current_post )
$classes[] = 'first-post';
return $classes;
}
add_filter( 'post_class', 'be_class_on_first_post' );
view raw functions.php hosted with ❤ by GitHub

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk