Automatically create meta description from the_content

Adding this snippet to the functions.php of your wordpress theme will automatically create a meta description from your wordpress post striping out all shortcodes and tags. Make sure you have in the header.php of your wordpress theme or this snippet will not work.

function create_meta_desc() {
    global $post;

if (!is_single()) { return; }

    $meta = strip_tags($post->post_content);
    $meta = strip_shortcodes($post->post_content);
    $meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
    $meta = substr($meta, 0, 125);

    echo "<meta name='description' content='$meta' />";

add_action('wp_head', 'create_meta_desc');

Comments  Leave a Reply

  1. As already mentioned (no clue why the author is not updating his mistake) strip/replace this code part: $meta = strip_shortcodes($post->post_content); with just: $meta = strip_shortcodes($meta); else it has no sence and is incorrect and looks terrible on google!

  2. BloodyGoodGames May 6, 2013 at 11:22 pm

    Wow,. that broke my site. As soon as you put it in the header you get an error code so it doesn’t work. Too bad as it’s exactly what I needed 🙁

    1. what is the error you get?

  3. Would you think possible to take H2 content from a post, limit the numbers of characters or word, and copy it into the description by default? Thanks!

  4. Sorry Pal, but here’s a correction on this algorithm:

    function create_meta_desc() {
    global $post;
    if (!is_single()) { return; }
    $meta = strip_tags($post->post_content);
    $meta = strip_shortcodes($meta); /* here you have to use the same variable, or else the strip_tags will not have any effect */
    $meta = str_replace(array(“n”, “r”, “t”), ‘ ‘, $meta);
    $meta = substr($meta, 0, 125);
    echo “”;
    add_action(‘wp_head’, ‘create_meta_desc’);

  5. 29 Wordpress Tweaks to Improve Posts and Pages October 19, 2011 at 9:01 am

    […] [Source: WpSnipp] […]

  6. Trieuquangkhanh August 3, 2011 at 6:03 am

    have HTML TAGS !

    1. I’m not sure what you mean? however HTML tags are stripped out using “strip_tags”

      1. no it isn’t. i had to add a strip_tags right before the substr() function, that worked

Add a Comment

We're glad you have chosen to leave a comment. Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

WordPress Launch Checklist

The Ultimate WordPress Launch Checklist

We've compiled all the essential checklist items for your next WordPress website launch into one handy ebook.
Yes, Send Me the Free eBook!