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

1 Answer
1

$query = new WP_Query( $args );

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

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

    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();
      break;

    ....

  }
endwhile; endif;
wp_reset_postdata();

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *