If I make a query to the wordpress database to pull the five most recent posts of some kind, and I would like to do a different treatment to each of them, is there a way to access the individual instance objects?

For instance, if I want to do something to the second post object, is there a way to access the object by something along these lines?

$query = new WP_Query( $args );

$query[1] => access to the second post object from the query
$query = new WP_Query( $args );

if ( $query->have_posts( $query->have_posts()) ) : while( $query->have_posts()) :
  global $post;
  switch ( $query->current_post ) {

    case 0 :
      // first post object is in var $post;
      echo 'The first post title is ' . $post->post_title;

    case 1 :
      // because we are insed the loop we can use all the post template tags
      echo 'The second post title is ' . get_the_title();


endwhile; endif;
  • 3
    Just a tip, you can count posts using the built in $query->current_post + 1; – Wyck Aug 19 '13 at 1:44
  • 1
    +1 edited answer. $query->current_post is enough because cases start with 0 @Wyck – gmazzap Aug 19 '13 at 1:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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