Use the Excerpt When a Yoast Meta Description Is Empty
Fills an empty Yoast SEO meta description with the post's excerpt (or its opening words), trimmed to a search-friendly length.
Opens WPIDE on
Code
// Maximum description length in characters.
$wpide_desc_length = 155;
add_filter( 'wpseo_metadesc', function ( $description ) use ( $wpide_desc_length ) {
if ( '' !== trim( (string) $description ) || ! is_singular() ) {
return $description;
}
$post = get_queried_object();
if ( ! $post instanceof WP_Post ) {
return $description;
}
$text = has_excerpt( $post ) ? $post->post_excerpt : strip_shortcodes( $post->post_content );
$text = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $text ) ) );
if ( mb_strlen( $text ) > $wpide_desc_length ) {
$text = rtrim( mb_substr( $text, 0, $wpide_desc_length - 1 ), " ,.;:-" ) . '…';
}
return $text;
} );
Notes
Descriptions set in Yoast, and Yoast's template descriptions, always win.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.