I would keep out of your header.php
& either add the following to your functions.php
or wrap up as a plugin:
add_action( 'wp_head', 'wpse_71766_seo' );
/**
* Add meta description & keywords for single posts.
*/
function wpse_71766_seo()
{
if ( is_single() && $post_id = get_queried_object_id() ) {
if ( ! $description = get_post_field( 'post_excerpt', $post_id ) )
$description = get_post_field( 'post_content', $post_id );
$description = trim( wp_strip_all_tags( $description, true ) );
$description = substr( $description, 0, 150 );
$keywords = array();
if ( $categories = get_the_category( $post_id ) ) {
foreach ( $categories as $category )
$keywords[] = $category->name;
}
if ( $tags = get_the_tags( $post_id ) ) {
foreach ( $tags as $tag )
$keywords[] = $tag->name;
}
if ( $description )
printf( '<meta name="description" content="%s" />' . "\n\t", esc_attr( $description ) );
if ( $keywords )
printf( '<meta name="keywords" content="%s" />' . "\n\t", esc_attr( implode( ', ', $keywords ) ) );
}
}
This hooks onto the wp_head
action & outputs the required meta only if currently viewing a single post.
Edit: Fixed two equal symbols that were missing.