YPSA Webmaster's Blog

Skip to content Skip to sidebar

How to create custom meta description for each individual posts in wordpress

In respect to search engine optimization, we may need to add unique meta description for each post so that search engines can show the predefined custom excerpt in their search results . We can do it creating a custom meta box for the posts.

We will write functions for appearing a text box below the post editor section where we will put our individual meta description. We will use post excerpt (first 150 characters) if the field is left blank.

Add bellow code in your functions.php

// 'Custom Meta Description' field below post 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 SEO meta description for this post  (if left empty, the first 150 characters of the excerpt will be used)', 'custom_meta_desc_input_function', 'post', 'normal', 'high');
function custom_meta_desc_input_function() {
global $post;
echo '<input id="custom_meta_desc_input_hidden" type="hidden" name="custom_meta_desc_input_hidden" value="'.wp_create_nonce('custom-meta-desc-nonce').'" />';
echo '<input id="custom_meta_desc_input" style="width: 100%;" type="text" name="custom_meta_desc_input" 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;
// Check permissions
 if ( 'page' == $_POST['post_type'] )
 if ( !current_user_can( 'edit_page', $post_id ) )
 return $post_id;
 if ( !current_user_can( 'edit_post', $post_id ) )
 return $post_id;
$customMetaDesc = $_POST['custom_meta_desc_input'];
update_post_meta($post_id, '_custom_meta_desc', $customMetaDesc);

Now we need to add following code within meta description of  header.php

<meta name="description" content="<?php
if( is_single()) :
$text = get_post_meta($post->ID,'_custom_meta_desc',true);
if(!$text) $text = ($post->post_excerpt) ? $post->post_excerpt : substr($post->post_content, 0, 150).'...';
echo esc_attr(strip_tags(apply_filters('get_the_excerpt',$text)));
if(is_home()){ echo "Your meta description for home page"; }
endif; ?>">

Enjoy it.

About the author

Abdullah Al Shakir

I am a web developer and graphics designer have been working in YPSA as webmaster since 2006. I am expert in XHTML, CSS, JavaScript and PHP programming. I am Wordpress theme and plugin developer. I am a father and husband living in Bangladesh.

You may also like

Leave a Reply