Skip to content

Instantly share code, notes, and snippets.

@zgordon
Last active June 2, 2021 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zgordon/950159056d2ad299b0ee to your computer and use it in GitHub Desktop.
Save zgordon/950159056d2ad299b0ee to your computer and use it in GitHub Desktop.
Add Meta Description to WordPress Theme
function custom_get_excerpt($post_id) {
$temp = $post;
$post = get_post( $post_id );
setup_postdata( $post );
$excerpt = esc_attr(strip_tags(get_the_excerpt()));
wp_reset_postdata();
$post = $temp;
return $excerpt;
}
function custom_add_meta_description_tag() {
?>
<meta name="description" content="<?php if ( is_single() || is_page() ) {
$excerpt = custom_get_excerpt(get_the_ID());
echo $excerpt;
} else {
bloginfo('description');
}
?>" />
<?php
}
add_action('wp_head', 'custom_add_meta_description_tag', 1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment