how to display an excerpt of the latest post on the homepage?
-
16-10-2019 - |
Question
I've got a CMS-style wordpress setup where the homepage is not the main blog posts page.
However, I would like to display the first paragraph of the latest blog post on the homepage, with a link to the post. How would I do that?
I'd also like to display, above this excerpt, the first image within the post, but I'm guessing that might be harder... or I'll have to use the 'featured image' or a custom field...?
Solution
To show the excerpt from the latest post you can use query_posts.
Example Query Posts Showing the Latest Post with the Featured Image:
<?php query_posts('showposts=1'); ?>
<?php while (have_posts()) : the_post(); ?>
<h3 class="home link"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php the_post_thumbnail(); ?>
<?php the_excerpt(); ?>
<?php endwhile; ?>
You will need to reset the query if you want to show content entered into your home page's post editor.
<?php wp_reset_query(); ?>
OTHER TIPS
Here's how you'd do that:
$post = get_posts( 'posts_per_page=1' );
if( !empty( $post ) ){
setup_postdata( $post );
the_post_thumbnail();
?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
<?php the_excerpt(); ?>
}
$post = $wp_query->post;
setup_postdata( $post );
I highly suggest using the featured image for that.