Skip to content

Instantly share code, notes, and snippets.

@morgyface
Last active January 13, 2018 12:45
Show Gist options
  • Save morgyface/eb7bab547119cf3d9d231550ba0ecc25 to your computer and use it in GitHub Desktop.
Save morgyface/eb7bab547119cf3d9d231550ba0ecc25 to your computer and use it in GitHub Desktop.
WordPress | Use post/page excerpt to generate meta description for SEO
<?php
$tagline = get_bloginfo ( 'description' );
$post_object = get_post();
$excerpt = $post_object->post_excerpt; // Get the raw excerpt, warts (tags) and all.
$content = $post_object->post_content; // Get the raw content.
$char_limit = 150; // Set the character length to 150, best practice for SEO.
echo '<meta name="description" content="';
if ( !empty( $excerpt ) ) { // If there is an excerpt lets use it to generate a meta description
$excerpt_stripped = strip_tags( $excerpt ); // Remove any tags using the PHP function strip_tags.
$excerpt_length = strlen( $excerpt_stripped ); // Now lets count the characters
if ( $excerpt_length > $char_limit ) { // Now work out if we need to trim the character length.
$offset = $char_limit - $excerpt_length; // This gives us a negative value.
$position = strrpos( $excerpt_stripped, ' ', $offset ); // This starts looking for a space backwards from the offset.
echo substr( $excerpt_stripped, 0, $position ); // Trim up until the point of the last space.
} else {
echo $excerpt_stripped; // The excerpt must be less than the char_limit so lets just print it.
}
} elseif( !empty( $content ) ) {
// If no excerpt exists we use the content, note the use of get_post as we are outside the loop.
$content_stripped = strip_tags( $content );
$content_length = strlen( $content_stripped );
if ( $content_length > $char_limit ) {
$offset = $char_limit - $content_length;
$position = strrpos( $content_stripped, ' ', $offset );
echo substr( $content_stripped, 0, $position );
} else {
echo $content_stripped;
}
} else {
echo $tagline; // If the page is empty we can use the tagline to prevent emptiness.
}
echo '">' . PHP_EOL; // close meta description.
?>
@morgyface
Copy link
Author

Now also available as a function, right here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment