Wordpress Snippets

Add Meta Description Tag Without Plugin in WordPress

First of all, I’d highly recommend using a dedicated SEO plugin like WordPress SEO or All in One SEO Pack to optimize your website for search engines because they are experts in this field and they really know what they are doing. Also it will be highly effective to use latest SEO techniques from expert plugins instead of just adding meta description tag to head section of your website. However sometimes you don’t have an option to use a SEO plugin and you just need a way to add meta description onto your pages. For such cases, we will show you how to add meta description tag in your website without using any plugin.

For the sake of simplicity, we will be using first few lines of post content and add these to meta description tags to website head section automatically. So you can have meta description tags on your website without having to change anything.

Simply paste this WordPress code snippet in your theme’s functions.php file. This function will automatically create meta description tag in your website.

// add meta description tag without plugin in wordpress
function wcs_add_meta_description_tag() {
    global $post;
    if ( is_single() ) {
        $meta = strip_tags( $post->post_content );
        $meta = strip_shortcodes( $post->post_content );
        $meta = str_replace( array("\n", "\r", "\t"), ' ', $meta );
        $meta = mb_substr( $meta, 0, 125, 'utf8' );
        echo '<meta name="description" content="' . $meta . '" />' . "\n";
    }
}
add_action( 'wp_head', 'wcs_add_meta_description_tag' , 2 );

Hire Us. Or just say Hi!
Need a job? Apply to get one.