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.

\$\endgroup\$
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 ;)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.