1

I'm trying to display a static front page with recent posts at the bottom. Specifically, I want to display just an excerpt from the recent posts, as would be returned by the_content() if I had a dynamic front page. What I've managed so far is to display the front page with the recent posts, but it's displaying the complete content of the posts not just the excerpt. I don't want to generate my own excerpts because I want them to be consistent with the excerpts that appear on the category and archive pages.

This is (a simplified version of) my front-page.php file at the moment:

<?php get_header(); ?>
<?php the_post(); ?>

<!-- This block is modified slightly from page.php -->
<a href="<?php bloginfo('url'); ?>">Home</a> &gt; <?php the_title(); ?>
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>

<div id="recent_posts">
<h2>Latest entries</h2>
<?php
$recent_posts_query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));

while ($recent_posts_query->have_posts())
{
$recent_posts_query->the_post();
?>
<div class="post">
<h3><?php echo the_title(); ?></h3>
<p>by <?php the_author(); ?></p>
<?php the_content(); ?>
</div>
<?php
}
?>
</div>

<?php get_footer(); ?>

How can I get the_content() to return just the excerpt? (Most of my posts have a <!--more--> tag in them, and those that don't I want appearing in full as they are short posts.)

EDIT: Tried using the_excerpt() but it returns an auto-generated excerpt even if the post contains a <!--more--> tag.

  • Please properly indent your code. Messy code is hard to debug and to read. Also, correct the markup in your question. Thank you – Pieter Goosen Jan 19 '16 at 19:13
  • @PieterGoosen I don't make a habit of indenting code because I frequently work with a blind programmer and he says that indented code is a pain for him to work with. Sorry about the mistakes in the markup. – Micheal Johnson Jan 19 '16 at 20:45
1

I've found the solution. According to https://codex.wordpress.org/Function_Reference/the_content#Overriding_Archive.2FSingle_Page_Behavior, one must add

global $more;
$more = 0;

before the call to the_content(). So now my inner loop reads:

<?php
$recent_posts_query = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 5));

while ($recent_posts_query->have_posts())
{
$recent_posts_query->the_post();
?>
<div class="post">
<h3><?php echo the_title(); ?></h3>
<p>by <?php the_author(); ?></p>
<?php
global $more;
$more = 0;
the_content();
?>
</div>
<?php
}
?>

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.