In my Elusive Music blog, I wanted to use custom excerpts, also known as manual excerpts. However, WordPress doesn’t automatically add a “Read More” link to a custom excerpt, just to automatically generated excerpts. I could have just added the link to custom excerpts, but I wanted to have the same “Read More” link for either type of excerpt.
The function elusive_custom_excerpt() handles three cases:
- A post with a custom excerpt
- A post with an automatically generated excerpt
- A short post that is complete, so adding “Read More” would be incorrect
Caveat I wanted “Read More” to follow the text on the same line instead of in a separate paragraph. That’s why there’s a call to the PHP function strip_tags(). It removes the paragraph tags around the excerpt, so that “Read More” is inside the paragraph. It also removes any other formatting, like bold and italic, unfortunately — a future enhancement perhaps.
The code
This function, along with the call to add_filter() that activates it, belongs in your theme’s functions.php.
/* * ---------------------------------------------------------------------------- * Add Read More tag after excerpt * ---------------------------------------------------------------------------- */ function elusive_custom_excerpt($text) { /* * Add a read-more tag to auto-generated and custom excerpts. Don't add read-more if the full text is the same as the excerpt. * * Tests: * If has_excerpt reports that there is a custom excerpt, append the read-more tag with the post's permalink * If it is an auto-generated excerpt with […] and a link appended, replace the hellip and link with our read-more tag * Else use the text passed to the function for the excerpt without a read-more */ $more = ' <a class="read-more" href="'.get_permalink().'">Read More...</a>'; $auto_more = '[…]'; if (has_excerpt($post_id)) { $excerpt = '' . strip_tags($text) . $more; } elseif (strpos($text, $auto_more)) { $excerpt = strip_tags(str_replace($auto_more, $more, $text), "<a>"); } else { $excerpt = $text; } return $excerpt; } add_filter('the_excerpt', 'elusive_custom_excerpt'); </a>
Types of “excerpts” in WordPress
You create a manual excerpt in the Excerpt box on the Edit Post page.
An automatic excerpt is created by WordPress when your post template uses the the_excerpt() template tag and there isn’t any manual excerpt. It contains the first 55 words of the post.
You create a teaser by adding the More shortcode to your post in the editor. WordPress uses the teaser when your post template has the the_content() template tag.
For more about excerpts, here’s a good page in the WordPress Codex, the official documentation.