Getting WordPress Excerpt Text to Post in Google+

I was getting very annoyed with Google+ whenever I’d link to an article on my blog. Instead of showing either the excerpt or the first “x” words of the article text, I’d see instead other administrative text from the source code. A little bit of coding fixed that up quickly and nicely.

What happens in Google+ (apparently) is that it’s looking for the description meta tag for the link text. A lot of WordPress themes don’t actually have that meta tag in the header—mine didn’t. And thus a little bit of code was necessary to fix things up.

<meta name="description" content="<?php if ( is_single() ) { echo htmlspecialchars( strip_tags( html_entity_decode( get_the_excerpt() ) ) ); } else { echo 'Insert generic website description here'; }?>" />

This needs to be inserted into your active header.php file somewhere between the <head></head> tags. This example only works for single posts, but it can be adapted. (Yeah, the code is smushed together here, but when it’s executed, the resulting HTML will look neat.)

What this does is check to see if this is a single post. If it is, then it gets the excerpt text and filters out any HTML tags and finally encodes potentially troublesome special characters. If it isn’t a single post, then it’ll output some generic text (or whatever you code in).

I’ve tested this (though not exhaustively) on both Google+ and Facebook, and no problems have yet arisen. YMMV, so use at your own risk.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.