add meta description to wordpress header

How to add meta descriptions to certain posts without a plugin?

Firstly I'd recommend trying an SEO plugin like All in One SEO to handle your search engine optimisation. However sometimes you might have a need to manually add a meta description onto a page. Or you may want to do something different on a particular post or page, in which case you could turn off the SEO plugin for that page and then add some custom code to your header.php file that only inserts it onto the applicable page(s).

Updates:

update 14/4/2013The original code for this did not take into consideration that you cannot use "the_excerpt" outside of the loop. The code below has been adjusted for this and instead of using "the_excerpt" it now uses "the_title". If you prefer to use "the_excerpt" in your header code, then there is some code further down this page that allows for using this outside the loop.For this exercise we are now going to use "the_title" and insert that into the header of your page, into the meta description. Paste the following code into your header.php file.<?php if (is_single() && in_category('1')) { ?>

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

<?php } ?>

So this would identify if the page is a single post and in category 1. If yes, then it adds meta description based on the_title. If you want to choose a range of posts, say with IDs 41,48,103 and 152, then you could use:<?php if is_single(array( 41,48,103,152 )) { ?>

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

<?php } ?>

or if you wanted to add the category description to the meta description of a category page, you could try:<?php if (is_category()) {

$cat = get_query_var('cat');

$metacat= strip_tags(category_description($cat));?>

<meta name="description" content="<?php echo $metacat;?>"/>

<?php } ?>

You can also set meta description based on "the_excerpt" using the following technique, which allows for calling "get_the_excerpt" outside of the loop. <?php if (is_single() || is_page() ) : if (have_posts() ) : while (have_posts() ) : the_post(); ?>

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

<?php endwhile; endif; elseif (is_home() ): ?>

<meta name="description" content="<?php bloginfo('description'); ?>- AND ADD SOME MORE CONTENT HERE">

<?php endif; ?>

This code will add the excerpt to the meta description on your posts and pages. Additionally it allows for you to further customise the meta description of your home page, by adding your bloginfo description as well as extra content for enhancing your SEO.[dtwd-related-posts-sc title="More SEO tips" count=3]

Comments: