Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I have been using this question to try to do this but I am having some difficutlty. I have a custom post type, media, and I am working on the archive-media.php template. I have it partially working in that when I delete the if condition out of the code it does add the class, but of course to every post. I have determined that $wp_query->current_post is not returning a value, so I feel I must not be using this right. I have the code in my functions.php file. The codex says that current_post is available in the loop, so I am a bit confused.

add_filter('post_class', 'my_post_class');
function my_post_class($classes){
  global $wp_query;
  if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';
  return $classes;
}
share|improve this question
    
I adjusted the title of this question to better reflect that this is to do with circumstances involving custom queries. –  byronyasgur Mar 23 '12 at 21:13

1 Answer 1

up vote 1 down vote accepted

I realised that $wp_query doesn't work for where I had customised the queries with WP_query. This is completely obvious I suppose when you know, but I didn't, so here is the adjusted code in case it benefits some other amateur! Note that $media_query, $events_query etc are the instances of WP_query which I had created myself on the respective archive pages when I did the custom queries, so you'd need to do your own versions of these using whatever you used for the queries. I say this in case someone thinks these were defined by wordpress and try to copy and paste. ( $wp_query itself on the other hand of course is. )

// Add css class 'last' to last posts in archive query [ used in conjunction with post_class('archive-post') ]
add_filter('post_class', 'last_post_class');
function last_post_class($classes) {
    // Regular Archives
  global $wp_query;
  if(($wp_query->current_post+1) == $wp_query->post_count)
        $classes[] = 'last';

    // Media Archive
    global $media_query;
  if(($media_query->current_post+1) == $media_query->post_count)
        $classes[] = 'last';

    // Events Archive
    global $events_query;
  if(($events_query->current_post+1) == $events_query->post_count)
        $classes[] = 'last';

    // Author Archive
    global $author_query;
  if(($author_query->current_post+1) == $author_query->post_count)
        $classes[] = 'last';

  return $classes;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.