There are problems with this part:
++$GLOBALS['wpdb']->current_post
There's no current_post
property of the wpdb
class, here you're most likely confusing the wpdb
class with the WP_Query
class.
Also we wouldn't want in general to modify the current_post
property of the global WP_Query
, it could surely "bite us" if we mess with the globals ;-)
Note that the current_post
property of WP_Query
is already doing the counting for us with $this->current_post++
; inside next_post()
, that's called within the_post()
. See here. So there's no need to increase it manually (++) within the loop.
Here's an example using the post_class
filter, with the help of a static variable:
add_filter( 'post_class', function( $classes )
{
static $instance = 0;
if( in_the_loop() )
$classes[] = ( 0 === $instance++ % 2 ) ? 'even' : 'odd';
return $classes;
} );
where we target post classes in the main query loop. Just remember to modify the even/odd classes and other restrictions to your needs.
Using the post_class
filter could mean better re-usability for our template parts.
Update
It looks like you're using the first version of @toscho's one-liner answer, creating a custom current_post
property (for counting) of the global wpdb
object. He suggested then to use the prefixed custom property, like wpse_post_counter
. But it looks like it needs an initialization to avoid the PHP notice.
@kaiser did post a great answer here that uses the current_post
property of the global $wp_query
(probably not the global $wpdb
).
Since I gave a promise here, regarding anonymous functions and global variables, I should rewrite it to: See my edit here
- where we use the use
keyword to pass on the global $wp_query
object.