A very important thing to pay attention to when optimizing your site for search engine ranking is creating unique pages meta descriptions for all of the pages on your website that you want to have indexed. If you take a look on Google, or any search engine, you will see a blurb about your page beneath the page title. This little bit of text is taken for the text your page has in the meta description tag. No text, no blurb on Google, and possibly no indexing whatsoever.

Google Example

Page description in Google

Having a unique title for each page is important, but what is more important is making sure that the description for your page is just as unique and relevant. The great thing about WordPress is that you can use some basic functions to put together a little script that would create a meta description dynamically for each of your pages.

I encountered a few issues trying to put this script together due to the fact that some plugins actually hook into the_content() or the_excerpt() and this causes a lot of issues. The final solution I came up with is below. Just add the following to your functions.php file within the PHP tags:

function dynamic_meta_description() {
	$rawcontent = 	get_the_content();
	if(empty($rawcontent)) {
		$rawcontent = htmlentities(bloginfo('description'));
	} else {
		$rawcontent = apply_filters('the_content_rss', strip_tags($rawcontent));
		$rawcontent = preg_replace('/\[.+\]/','', $rawcontent);
		$chars = array("", "\n", "\r", "chr(13)",  "\t", "\0", "\x0B");
		$rawcontent = htmlentities(str_replace($chars, " ", $rawcontent));
	}
	if (strlen($rawcontent) < 155) {
		echo $rawcontent;
	} else {
		$desc = substr($rawcontent,0,155);
		return $desc;
	}
}

This little script grabs the raw content using get_the_content(), then it applies some filters and removes shortcodes, tags and line breaks. Once that is done, it limits the description to 155 characters if it is too long. Finally it returns the description, formatted exactly how you need it to be.

Next all we need to do is add a line to the header.php between the head tags.

<meta name="description" content="<?php echo dynamic_meta_description(); ?>" />

If a meta description line already exists, you can replace it with this.

Now all of your pages will have a unique meta description, and those that don’t will have your default site description, which you set up in your wp-admin under your General Settings.