How to Auto-generate Meta Description in WordPress

When it comes to blogging and search engine optimization, no other on-page element is as important as title and meta descriptions. According to Google search console guidelines, every page on a WordPress blog must have unique meta description and title.

If you don’t follow this guideline, your site won’t rank well in search engines, and if you’ve verified your blog with Google Search Console, you’ll see duplicate tag warning in HTML improvements section of your Google Search Console account. Meta description is one of the most important on-page elements as it is the first thing that a search engine users see (if your site appears in the search results) when they search for some information. If you’ve not added relevant keyword and a useful short information in this tag, the user will not visit your blog. Meta description length should not be less or more than 170 characters, and it shouldn’t be stuffed with keywords.

Option 1

You can define with variables like if you want your excerpt content to be used as meta description then use %excerpt%

 

But in this case if the length of excerpt goes beyond the limit of meta description content length then it will not be a good practice to improve SEO.

To avoid this kind of situation we can go for option 2 which is more accurate in terms of meta description content length but yes there might be missing of keywords or the meta description is incomplete.

Option 2

In option two we need to add custom function to automatically assign meta description based on excerpt and content of the post/blog.

function create_meta_desc() { 
    global $post; 
    $chars = 160;
    if (!is_singular()) {return; } 
    elseif(!empty( $post->post_excerpt)) { 
        $excerpt = $post->post_excerpt;
        if($chars < strlen($excerpt)) 
        {
            $excerpt = substr($excerpt, 0, $chars);
            $space_pos = strrpos($excerpt, " ");
            if($space_pos >= 0) 
                $excerpt = substr($excerpt, 0, strrpos($excerpt, " "));
        }
        echo "<meta name='description' content='$excerpt' />"; 
    } 
    else { 
        $content = apply_filters('the_content', $post->post_content); 
        $content = strip_tags($content); 
        $content = strip_shortcodes($content ); 
        $content = str_replace(array("\n", "\r", "\t"), ' ', $content); 
        if($chars < strlen($content)) 
        {
            $content = substr($content, 0, $chars);
            $space_pos = strrpos($content, " ");
            if($space_pos >= 0) 
                $content = substr($content, 0, strrpos($content, " "));
        }
        echo "<meta name='description' content='$content' />"; 
    } 
} 
add_action('wp_head', 'create_meta_desc');