Auto generate meta description tag in WordPress without plugins

Meta Description SEO Auto generate meta description tag in WordPress without plugins

Meta description tag is an important factor for Search Engine Optimization (SEO). Search engines use it for display page snippet in Search Engine Result Pages (SERPs). Via meta description tag (snippet) 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 built-in feature for auto generation meta description tag. But you can do it yourself without any plugins, and here it is!

Simply paste the following code into your functions.php file of your theme:

add_action( 'wp_head', 'gen_meta_desc' );
function gen_meta_desc()
{
    global $post;

    if ( ! is_singular() )
        return;

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

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

Change the 125 to number of characters you want to show in meta description tag.

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

About Tran Ngoc Tuan Anh

Also known as Rilwis. A web, WordPress developer. Freelance. Founder of Deluxe Blog Tips and Look4WP. Loves books, Internet & technology.

Comments

  1. Ed Nailor says:

    Love the idea, but noticed your code was checking for a single post. I am assuming that this will work with pages as well, removing that single check… Correct?

  2. Narciso says:

    Hi,
    From where will descriptions be taken?

    Thanks

Speak Your Mind

*