Mini SEO – a Meta Description Field for Posts and Pages

Modern search engines do not rely on meta descriptions and meta keywords anymore for your ranking.

However, they do preferably show a proper added meta description instead of the first few words of the post or page.

If you can enter this meta description into your WordPress blog or CMS, specifically for each post and static page, you can fine tune what you would like your customers to see with the search results.

Most users would download and install one of the many SEO plugins, which often come with a lot of unwanted features.

With a bit of programming, you can add your own ‘Meta Description Field’ below the post/page editor.

The first part of the code needs to be added into functions.php of your theme:

// 'Custom Meta Description' field below post/page editor
add_action('admin_menu', 'custom_meta_desc');
add_action('save_post', 'save_custom_meta_desc');
function custom_meta_desc() {
add_meta_box('custom_meta_desc', 'Add meta description <small>(if left empty, the first 200 characters of the excerpt will be used)</small>', 'custom_meta_desc_input_function', 'post', 'normal', 'high');
add_meta_box('custom_meta_desc', 'Add meta description <small>(if left empty, the first 200 characters of the excerpt will be used)</small>', 'custom_meta_desc_input_function', 'page', 'normal', 'high');
}
function custom_meta_desc_input_function() {
global $post;
echo '<input type="hidden" name="custom_meta_desc_input_hidden" id="custom_meta_desc_input_hidden" value="'.wp_create_nonce('custom-meta-desc-nonce').'" />';
echo '<input type="text" name="custom_meta_desc_input" id="custom_meta_desc_input" style="width:100%;" value="'.get_post_meta($post->ID,'_custom_meta_desc',true).'" />';
}
function save_custom_meta_desc($post_id) {
if (!wp_verify_nonce($_POST['custom_meta_desc_input_hidden'], 'custom-meta-desc-nonce')) return $post_id;
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return $post_id;
$customMetaDesc = $_POST['custom_meta_desc_input'];
update_post_meta($post_id, '_custom_meta_desc', $customMetaDesc);
}

The second part will be added into header.php, below the <title> tag:

<meta name="description" content="<?php
if( is_single() || is_page() ) :
$text = get_post_meta($post->ID,'_custom_meta_desc',true);
if(!$text) $text = ($post->post_excerpt) ? $post->post_excerpt : substr($post->post_content, 0, 200).'...';
echo esc_attr(strip_tags(apply_filters('get_the_excerpt',$text)));
else :
/* optional area to program meta descriptions for index and archive pages, etc */
endif; ?>" />

meat description input field
'Meta Description Input' for posts and pages

The new input field will show directly below the post or page editor window.

Simply add your meta description text into the field, and press the usual ‘update’ button;
if left empty, the meta description will show the first 200 characters of the post or page.