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

Radically overhauled in September 2017. Tested and working perfectly.

@morgyface
Copy link
Author

morgyface commented Sep 8, 2017

More amendments. Not working that perfectly. I found using the strpos thing wasn't working that well, mainly because if the strpos position was in the middle of the final word, it would look beyond it and not find any spaces, it therefore returned false. So, I've used strrpos (note two r's) combined with a negative value offset which means it looks backwards from the offset and is guaranteed to find a space, unless of course the string is a single word longer than 150 characters. Which is possible in Wales I suppose.

@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