Add Meta Description Box without Plugins on WordPress

meta-dscrition

How To Add Meta Description Box

1st Step

  • Open functions.php first.
  • Now paste given code there.
// Add meta box
function custom_meta_box() {
add_meta_box(
'custom-meta-box',
__('Meta Description', 'textdomain'),
'custom_meta_box_callback',
'post', // Change this to 'page' if you want the meta box on pages
'side',
'high'
);
}
add_action('add_meta_boxes', 'custom_meta_box');

// Meta box callback function
function custom_meta_box_callback($post) {
$meta_description = get_post_meta($post->ID, '_custom_meta_description', true);
?>
<p>
<label for="custom-meta-description"><?php _e('Meta Description:', 'textdomain'); ?></label>
<br>
<textarea id="custom-meta-description" name="custom-meta-description" rows="6" style="width:100%"><?php echo esc_textarea($meta_description); ?></textarea>
<br>
<span id="char-count" class="description"><?php printf(__('Characters entered: %d / 160', 'textdomain'), strlen($meta_description)); ?></span>
</p>
<script>
jQuery(document).ready(function($) {
var maxChars = 160;
var $metaDescription = $('#custom-meta-description');
var $charCount = $('#char-count');

$metaDescription.on('input', function() {
var enteredChars = $(this).val().length;
$charCount.text('Characters entered: ' + enteredChars + ' / ' + maxChars);

if (enteredChars > maxChars) {
$charCount.css('color', 'red');
} else {
$charCount.css('color', 'inherit');
}
});

// Enforce character limit
$metaDescription.on('input', function() {
if ($(this).val().length > maxChars) {
$(this).val($(this).val().substring(0, maxChars));
}
});
});
</script>
<?php
}

// Save meta description
function save_custom_meta_description($post_id) {
if (isset($_POST['custom-meta-description'])) {
$meta_description = sanitize_textarea_field($_POST['custom-meta-description']);
update_post_meta($post_id, '_custom_meta_description', $meta_description);
}
}
add_action('save_post', 'save_custom_meta_description');
  • Now click to UPDATE FILE button for save or apply changes.

2nd Step

  • Open header.php file then paste code
 <?php
if (is_single() || is_page()) {
$meta_description = get_post_meta($post->ID, '_custom_meta_description', true);
if (!empty($meta_description)) {
echo '<meta name="description" content="' . esc_attr($meta_description) . '" />' . "\n";
}
}
?>
  • Now click to UPDATE FILE button for save or apply changes.

Optional Code

If you want to show Meta Description on Post so paste given code there you want to show Meta Description.

 <?php $meta_description = get_post_meta(get_the_ID(), '_custom_meta_description', true);
if ($meta_description) {
echo '<div class="meta-description">' . esc_html($meta_description) . '</div>';
}
?>

Use this code and show Meta Description on Post.

Hope this code will work on Your WordPress Theme. Thanks for visiting.