avatar Deluxe Blog Tips About Projects

Auto generate meta description without plugins in WordPress

Meta description is an important factor for Search Engine Optimization (SEO). Search engines use it for display snippet in the search results. Via meta description, visitors can see a brief and concise summary of your page's content. In WordPress, if you use SEO plugins like All-In-One SEO, it already has the built-in feature for auto generation meta description tag. But you can do it yourself without any plugins, and here it is!

Updated: the code below is outdated. Please use the Slim SEO plugin to get the job done automatically.

Meta Description Tag
How meta description appears in search results

The idea of generating meta description is getting the first paragraph of your post and remove all formats, truncate it to a appropriated length so search engines can understand and display it correctly.

To do that, simply paste the following code into your functions.php file of your theme:

add_action( 'wp_head', 'prefix_meta_desc' );
function prefix_meta_desc() {
    if ( ! is_singular() )
        return;

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

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

The code above will run only in singular pages (pages, single posts and all single custom post types). It removes all HTML tags from the post content, replaces all special whitespace characters (tabs, new lines) to a single space and truncates it to 155 characters.

Be sure that you added wp_head() in your theme header.php file.

Why should meta description have 155 characters?

According to the study of MOZ, the appropriate length of meta description is around 155 characters. The search engines don't recommend an exact number because it depends on which language of your website and the length of the words.

Meta descriptions can be any length, but search engines generally truncate snippets longer than 160 characters. It is best to keep meta descriptions between 150 and 160 characters.

Now you can forget the SEO plugins and makes your theme optimized for SEO. If you find anything interesting about SEO or meta description tag, please let me know in the comments.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Comments