Rank Math Description Fallback From the Excerpt
Fills an empty Rank Math meta description on posts and pages with the excerpt or opening text, trimmed to about 155 characters.
Opens WPIDE on
Code
// Maximum description length.
$wpide_rm_desc_length = 155;
add_filter( 'rank_math/frontend/description', function ( $description ) use ( $wpide_rm_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_rm_desc_length ) {
$text = rtrim( mb_substr( $text, 0, $wpide_rm_desc_length - 1 ), " ,.;:-" ) . '…';
}
return $text;
} );
Notes
Descriptions you write in Rank Math 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.