I think you want to to this on singular post/page, so you don’t think to setup global post object, it is already set up.
After that, the problem is that calling get_excerpt
will run some filters that add html entities.
This is because get_the_excerpt
is intended to be used in page content (inside the <body>
part) and there is a side effect, when no manual excerpt is on page, that function also call the the_content
filter, that can cause some compatibility problems with plugins… so what I suggest is do not use that function to exctract the description, but use some low level functions:
After a very quick test, I think this should be good, but probably can be improved:
in functions.php
function head_description( $desc="" ) {
$desc = str_replace( '"', '', html_entity_decode( $desc ) );
$desc = stripslashes( wp_filter_nohtml_kses( $desc ) );
return str_replace( '&', '&', $desc );
}
Then in header.php
<head>
<?php
if ( is_singular() ) {
global $post;
$excerpt = $post->post_excerpt ? : wp_trim_words( $post->post_content, 55, '' );
$desc = head_description( $excerpt );
} else {
$desc = head_description( 'Foo' ); // description for non singular pages
}
?>
<meta name="description" content="<?php echo $desc; ?>">
<?php } ?>
Be sure to use double quotes in content=" ... "
because single quote in description are not escaped and so you have problems if you use single quote to wrap content.