Syntax to get the Nth item in a list of custom post types?

Make use of an offset to skip the first 2 posts if you need the third post only, and then set you posts_per_page to 1 to get only that specific post

You can try something like this in your arguments

$args = array(
    'post_type' => 'testimonial',
    'offset' => 2,
    'posts_per_page' => 1
);
$testimonials = new WP_Query( $args );
    while( $testimonials->have_posts() ) {
    $testimonials->the_post();
?>
    <li>
        <?php the_content(); ?>
    </li>

<?php }
wp_reset_postdata(); ?>

EDIT

Before I start, a few notes on your code and my edited code. (I have edited my original code to show a normal loop).

  • You don’t need to use echo get_the_content(). You can just use the_content() directly

  • Remember to reset your postdata after the loop with wp_reset_postdata().

As requested in comments, here is the alternative syntax where you don’t use the loop. Also, a note or two first:

  • With this alternative syntax, you cannot use the template tags as they will not be available

You need to work with the WP_Post objects directly and use filters as described in the link

  • You don’t need to reset postdata as you are not altering the globals

You can try

$args = array(
    'post_type' => 'testimonial',
    'offset' => 2,
    'posts_per_page' => 1
);
$testimonials = new WP_Query( $args );

//Displays the title
echo apply_filters( 'the_title', $testimonials->posts[0]->post_title );

//Displays the content
echo apply_filters( 'the_content', $testimonials->posts[0]->post_content );

Leave a Comment