2
\$\begingroup\$

Here's the code I'm planning to use to power meta description tags for a site in header.php in the template. Is anything missing / incorrect / could be done better?

<?php
if (is_front_page() || is_home()) {
 $description = get_bloginfo('description');
} else {
 $description = get_post_meta(get_the_ID(), 'description', true);
} 
if ($description) {
 ?>
 <meta name="description" content="<?php echo htmlspecialchars($description); ?>" />
 <?php
}
?>

In case anyone's wondering if meta descriptions have any value these days:

Google will sometimes use the meta description of a page in search results snippets, if we think it gives users a more accurate description than would be possible purely from the on-page content. Accurate meta descriptions can help improve your clickthrough...

Source

EDIT:

A little explanation is I want to make sure there aren't any cases where this breaks something or doesn't print a description when it should or prints the wrong description. I've tested it and it seems to work pretty well, but you don't know what you don't know.

asked Feb 2, 2016 at 6:19
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

What if your $description variable is empty? You are only checking if you're on the front page, or home page, and set it to blog description from wordpress, and if you're not, you're setting it to your post meta value.

What about categories? Tags? other archive pages?

The

if($description)

Will return what? False. Why? Because it's a description, not a boolean.

You should check it with

if(isset($description) && $description !== '')

If the variable is set and not empty string you'll get a true as a value that will pass the if test.

I'd do it like this:

<?php
if (is_page() || is_single()) {
 $description = get_post_meta(get_the_ID(), 'description', true);
} else {
 $description = get_bloginfo('description');
}
if (isset($description) && $description !== '') {
 ?>
 <meta name="description" content="<?php echo htmlspecialchars($description); ?>" />
 <?php
}
?>

If you're on a single post or a page, you'll get the post meta, and if you're anywhere else, you'll get blog description. And then output it only if it's set and not empty.

My advice is to see all the cases that can come up with conditional tags and set your description accordingly ;)

answered Mar 3, 2016 at 9:12
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.