Home / functions.php / Automatically create meta description from the_content
  • 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.

    wordpress snippet : PHP

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

    ( WordPress codex functions, hooks, in this snippet. )

    wp_head, is_single, add_action, strip_shortcodes, wp,
  • 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?

  • Henry Levin

    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!

Build a better with wpsnipp.com

Weekly snippets, themes, deals coupons roundup.

x No Thanks