Setting Up "Read More" Links That Only Display For Excerpts on WordPress
A little while back I posted an article on using manual excerpts with read more links on the home page of your blog. In that article I mentioned that there was only one drawback to the method I was describing: the "read more" link we created wasn't controlled by the same "if statement" that displayed the excerpt, so it would show up even on posts that didn't actually have an excerpt (and were therefore already displaying their full content).
Certainly not the end of the world, but definitely unnecessary. Today we fix that problem by adding some code to your theme that will display the link only if it's actually needed.
Now if you read the post in question, you'll probably remember that we called the excerpt like this:
<?php
if (function_exists('has_excerpt') && has_excerpt()) the_excerpt();
else the_content('Read on...');
?>
Which worked pretty well. The adjustment we're going to make today, so that our custom read more link is conditional, is a pretty simple one (which is why I feel silly for not thinking of it while I was writing the original post ;)). All we need to do is add another conditional statement after the excerpt is displayed.
<?php
if (function_exists('has_excerpt') && has_excerpt()) { ?>
<a href="<?php the_permalink() ?>" title="Continue Reading <?php the_title_attribute(); ?>...">Read the rest of <?php the_title(); ?> »</a>
<?php } ?>
All we're doing here is repeating the check to see if an excerpt is present (just like above). Only this time, instead of actually displaying the excerpt, we break out of PHP for a moment to add our read more link.
You'll notice I got a little fancier with the link this time around so that the title of the post in question is included in the title tag (using the_title_attribute()) as well as in the actual anchor text (using the_title()).
Don't forget to open up a final pair of PHP tags to close out the curly braces that contain the if-statement's actions.
There you go! You now have a link that not only contains the actual name of the post that it goes to, but will only display when it's needed. This also solves the problem of using the occasional More Tag for a post... with this code added into the mix, you won't need to worry about having two links show up!
Enjoy!
--
Chad is the author of www.WelcomeToWordPress.com, a blog dedicated to helping you create and optimize your very own WordPress blog with articles, tips, and step-by-step video tutorials.
Proven, automated, easy-to-use tracking tool that gives you 'psychic' ability with every marketing step you take
About the Author: Lynne And Chad
Member Since: 09/02/2008
Company: Choose To Be Independent, LLC
Industry: Marketing and Advertising
Primary Web Site: http://OnlineBusinessAndMarketingCoaches.com

