wordpress snippets last updated   : September 29, 2014
we now have 639 snippets

Automatically create meta description from the_content

wordpress snippet

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.

snippet :  PHPcopy
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');
source →

Did you like this post? If so please share it with your friends. Thanks!

  • Trieuquangkhanh

    have HTML TAGS !

    • http://wpsnipp.com Kevin Chard

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

      • w_z_a

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

  • Pingback: 29 Wordpress Tweaks to Improve Posts and Pages

  • Henrique

    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’);

  • Propagan

    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!

  • http://www.bloodygoodgames.com/ BloodyGoodGames

    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 :(

    • http://wpsnipp.com Kevin Chard

      what is the error you get?