Cheat Sheet: Wordpress excerpts
It’s common on blogs that post long articles to store a shorter or excerpted portion of the post in the database — this excerpt can then be used where many posts are listed on a page. If a viewer wants to read the whole post, they can click into the permalink version to see it. There are at least two ways to do this kind of thing in Wordpress:
Using Excerpts
Create a new post and make sure the Excerpt field is visible (check Screen Options if you don’t see it). Try writing a long post in the main Content field and a shorter summary in the Excerpt field.
Now you can insert the_excerpt
into your template. However, you may want to combine it with a conditional to control which pages show excerpts and which show the full content. Here’s an example
<?php
if ( is_single() ) { // test to see if we're on a permalink page
the_content(); // show the post content
} else { // but otherwise (home page, category page, tag page, archive page)
the_excerpt(); // just show the excerpt
} ?>
But sometimes you’re using the Excerpt field in your post for some other purpose. In this case, the default usage can backfire.
Using the more
divider
Try another test: leave your Excerpt empty but write a longish post in the Content area. Now put your cursor between two paragraphs. Find the more
button in the editing toolbar (shown at left) and click it to insert the more
divider.
This now divides your post: the part above more
is the excerpt, while the entire post is your content.
The Excerpt Gotcha
Wordpress tries to be a little too helpful sometimes. If you leave the Excerpt field empty, and your template calls the_excerpt()
function, Wordpress will auto-generate an excerpt from the first 55 words of your Content and tack on an ellipsis (…) at the end.
So if you don’t want this behavior, and you literally want to grab the contents of the Excerpt field (even if it’s empty), use the object-oriented version like this:
echo $post->post_excerpt; // like the_excerpt() except it will (logically) output nothing if the Excerpt field is empty.