WordPress loop that shows first post only?

Here is what I am trying to do…

I am trying to display the first post only in my header, sort of like a featured post. I have it displaying like I want to, but it’s looping through all of the posts, so instead of showing only one post it’s showing all of the posts in my header.

Read More

Here’s my code:

<?php $i = 0; ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>
<?php $i++ ?>
<div class="post<?php if ($i == 1) echo ' first'; ?>">
*content to display post here*
</div>
<?php endwhile; ?>
<?php endif; ?>

Related posts

Leave a Reply

2 comments

  1. The easiest way to get the one latest post (in any category) is to use wp_get_archives() | Function | WordPress Developer Resources. Read the docs to change the category, etc.

    <?php
    echo wp_get_archives( 'type=postbypost&limit=1&format=custom&echo=0');
    ?>
    

    But if you want to use a WP new query, try this:

    <?php $my_query = new WP_Query('category_name=popular&showposts=1'); ?>
    
    <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
    
    <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
    
    <?php the_title(); ?></a>
    
    <?php the_content(); ?>
    
    <?php endwhile; ?>
    

    Change category_name to your category or delete that variable to show the most recent one post from any category. get rid of the linked title, too, if you don’t want it. Change

    <?php the_content(); ?>
    

    to

    <?php the_excerpt(); ?>
    

    to show an excerpt instead.

    See Function Reference/WP Query « WordPress Codex

    And a shortcode that shows the title and link to the most recent post is this; put in functions.php :

    // Most Recent Post
    function most_recent_post_shortcode() {
        return wp_get_archives( 'type=postbypost&limit=1&format=custom&echo=0');
    }
    add_shortcode( 'recent-post', 'most_recent_post_shortcode' );
    

    And then use this shortcode in the post/page editor:

    [recent-post]