Last active
January 13, 2018 12:45
-
-
Save morgyface/eb7bab547119cf3d9d231550ba0ecc25 to your computer and use it in GitHub Desktop.
WordPress | Use post/page excerpt to generate meta description for SEO
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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. | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Now also available as a function, right here.