Notice: Undefined property: wpdb::$current_post What can be wrong?

I’m working on a WordPress site and I use the following code to show posts in two columns on archive and category pages:

<div id="post-<?php the_ID(); ?>" <?php post_class( 0 === ++$GLOBALS['wpdb']->current_post % 2 ? 'grid col-340 fit' : 'grid col-340' ); ?>>

With debug set to “true” I got the following notice:

Notice: Undefined property: wpdb::$current_post in D:\beta\\wp-includes\wp-db.php on line 684

What can be wrong with this code? I noticed that this notice appeared with WordPress version 4+

Any help will be greatly appreciated. Thanks.

Solutions Collecting From Web of "Notice: Undefined property: wpdb::$current_post What can be wrong?"

There are problems with this part:


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.


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.

use get_the_ID() to get the current post id

<?php echo get_the_ID(); ?>

and this is how you call Global variable in wp global $wpdb;;