Skip to content

Adding WordPress meta descriptions without the need of any plugin.

It is possible to create meta descriptions automatically in WordPress for every post, page or category.

function create_meta_description() {
        global $post;
        if ( is_singular() ) {
        $current_post = strip_tags( $post->post_title." created:".$post->post_date.", last modified:".$post->post_modified." ".$post->post_content );
        $current_post = strip_shortcodes( $current_post );
        $current_post = str_replace( array("\n", "\r", "\t"), ' ', $current_post );
        $current_post = mb_substr( $current_post, 0, 300, 'utf8' );
        echo '<meta name="description" content="' . fix($current_post) . '" />' . "\n";
    }
    if ( is_home() ) {
        echo '<meta name="description" content="' . fix(get_bloginfo( "description" )) . '" />' . "\n";
    }
    if ( is_category() ) {
        $current_category = strip_tags(category_description());
        echo '<meta name="description" content="' . fix($current_category) . '" />' . "\n";
    }
}
add_action( 'wp_head', 'create_meta_description');

Add above function to your theme’s functions.php (“wp-content/themes/(theme_name)/functions.php, it’s best to create a child theme first but not necessary.

There are three functions describing the type of content, is_category, is_home and is_singular (a single page).

If you look at the is_singular function there are some adjustments which can be made, currently i’ve added the creation post_title, post_date,post_modified and post_content to the description. The fix() function removes all the html tags found and the trim() function remove’s any spaces left. Afterwards the whole piece is limited to 300 characters with the mb_substr function. If you have any comments please leave a comment! And enjoy your ease meta descriptions without the use of any plugin!

Leave a Reply

Your email address will not be published.

PHP Code Snippets Powered By : XYZScripts.com