The One with the Thoughts of Frans

Using WordPress Excerpts in Meta Description

For a long time I’ve been aware of the fact that few, if any, WordPress themes seemed to do anything with the META element’s description feature. I never bothered to look into a solution, especially since I never used to add excerpts to my posts half a decade ago. However, I’ve bothered to do so ever since I started notifying people about updates on Twitter. It already makes the search results much more readable if you’re looking for something in the archives of this site, and I figured I should do the same for search engines.

Some uneventful searching later I found what I was looking for, but it definitely wasn’t right for me: I’ve got a huge volume of posts without any excerpts, so printing empty descriptions no matter what would be silly at best, and besides there are more descriptions out there than merely those of posts. After all, categories and even my site itself have a description as well. The comment by Matthew Slyman was much more to my liking, which I then customized as follows:

<?php
$desc;
if ( is_single() ) {
	$desc = get_the_excerpt();
}
elseif ( is_page() ) {
	$desc = get_the_excerpt();
}
elseif ( is_category() ) {
	$desc = category_description();
}
elseif ( is_home() ) {
	$desc = get_bloginfo('description');
}
$desc = htmlspecialchars(trim(strip_tags($desc)));
if (!empty($desc)) {
	echo '<meta name="description" content="';
	echo $desc;
	echo '"/>';
}
?>

Add the whole thing anywhere in your HEAD element in header.php. If excerpts seem to be missing from pages, there’s a simple solution. If you want to reuse the code above for some reason, wrap some sort of function around it and stick it in functions.php. Enjoy.

Leave a Comment

You must be logged in to post a comment.