How to show Post Excerpts as Meta Descriptions


Hi, how to set Post Excerpts as Meta Description.



Hi Thierry Muller,

I'm a new to coding. I understood the code from first link and if I'm right its for showing short description text. But I wish to set below the title tag meta name="description" content="This is content is took from excerpt - meta description for SEO"


I'm able to set the excerpt as meta name description using this

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

under this section of header.php in template folder

beans_add_smart_action( 'beans_head', 'beans_head_meta', 0 );

function beans_head_meta() {

  ?>
  <meta charset="<?php esc_attr_e( get_bloginfo( 'charset' ) ); ?>" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="description" content="<?php echo esc_attr(htmlentities(get_the_excerpt()));  ?>" />
 <?php

}

But when I reload the webpage, the meta name="description" field is showing above

<meta name="Description" content="All Mobile brands">
<title> page title </title>

Can you tell me how can I bring the meta name below title tags


Hey Venkatesh,

You can either using beans_head hook or wp_head depending on where you want to add the meta tag (you may also adapt the action priority accordingly). Note that the order doesn't matter for search engines though. Here is the snippet I would suggest:

add_action( 'beans_head', 'example_head_meta' );

function example_head_meta() {

 global $post;

 // Return the excerpt() if it exists other truncate.
  if ( ! empty( $post->post_excerpt ) ) {
   $content = $post->post_excerpt;
 } elseif ( ! empty( $post->post_content ) ) {
   $content = wp_trim_words( $post->post_content, 40, '...' );
 } else {
    return;
 }

 ?>
  <meta name="description" content="<?php echo esc_attr( strip_tags( stripslashes( $content ) ) ); ?>" />
 <?php

}

You will notice that we have a condition to check if the excerpt exists, if note we use the post content and troncate it and if the post content is empty, we prevent the meta from loading.

Hope that helps,


Thanks Thierry Muller, did exactly what I wanted.

Write a reply

Login or register to write a reply, it's free!