How to see if a Post in WordPress has an Excerpt

On the single post page for our posts, we wanted to display the excerpt only if one had been entered. Since the built-in WordPress function to get the excerpt for a post will automatically generate one for you, we couldn’t just put the function in our post loop like what was done below.

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
	<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
		<h1 class="entry-title"><?php the_title(); ?></h1>
		<div class="entry-content">
			<?php the_excerpt(); ?>
			<?php the_content(); ?>
		</div><!-- .entry-content -->
	</div><!-- #post -->
<?php endwhile; // end of the loop. ?>

Doing this causes the intro of the post to show twice, once from the auto-generated excerpt and once in the post content. To fix this, we added a quick check to the post loop. Simply replacing the_excerpt function in the post loop with this little piece of code removed the double intro.

<?php 
	if( !empty($post->post_excerpt) ) {
		//We have a excerpt so print it
		the_excerpt();
	} 
?>

Related Posts

  1. Harness the Power of the WordPress Post Class Function and Style Those Sticky Posts
  2. Displaying custom post types on your WordPress blog homepage
  3. Where to Start with jQuery Selectors
  4. Awesome WordPress Feature of the Day: Add Theme Support
  5. 8 Must-Have WordPress Plugins to Improve SEO, Speed, and Security
This entry was posted in WordPress and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">