I have a new custom post type set up that will be where an online copy of our email newsletter lives, like any web-based archive of newsletters.

I am trying to create a conditional statement to add to the custom post type's single.php template so that on the most recent post, additional content is displayed.

The purpose of this is so that we can email subscribers a link to the latest newsletter for them to view on the website, which would include relevant ads and news above and below the content. Why? Because on newsletters that are NOT the very latest issue, the ads and news is irrelevant, and shouldn't be displayed.

Is there a way I can query my single.php template loop to only display content on the most recent post in this post-type?

Something like:

if ( is_most_recent_post('post_type=newsletter') ) {
  echo 'Content that shows up only in the most recent post in the Newsletter post type is output here.';

I know that function doesn't actually exists. It's hypothetical code. I hope this makes sense - thanks in advance for the tips!


Firstly you'd be better off creating a template file for your specific post type by creating a file called single-newsletter.php. WordPress will pick it up and use it automatically.

Secondly add this function to your functions.php and call it to work out if it's the most recent one:

function is_latest_newsletter( $post_id = 0 ) {
    $latest = array_shift( get_posts( array(
        'post_type' => 'newsletter',
        'posts_per_page' => 1
    ) ) );

    if ( ! $post_id && in_the_loop() )
        $post_id = get_the_ID();

    return $latest->ID == $post_id;

Then in your template file:

if ( have_posts() ) : while ( have_posts() ) : the_post();

    if ( is_latest_newsletter() ) {
        // do stuff

endwhile; endif;

You could also pass in a specific post ID to the function so it's usable in other contexts too.

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.