Print a meta description on every post and page from its excerpt, and on the homepage from your tagline.
add_action( 'wp_head', function (): void {
if ( defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'SLIM_SEO_VER' ) || defined( 'SEOPRESS_VERSION' ) || defined( 'AIOSEO_VERSION' ) ) {
return;
}
$description = '';
if ( is_singular() ) {
$post = get_queried_object();
$description = has_excerpt( $post ) ? get_the_excerpt( $post ) : wp_trim_words( wp_strip_all_tags( strip_shortcodes( $post->post_content ) ), 28, '…' );
} elseif ( is_front_page() || is_home() ) {
$description = get_bloginfo( 'description' );
} elseif ( is_category() || is_tag() || is_tax() ) {
$description = wp_strip_all_tags( term_description() );
}
$description = trim( preg_replace( '/\s+/', ' ', (string) $description ) );
if ( '' !== $description ) {
printf( '<meta name="description" content="%s">' . "\n", esc_attr( mb_substr( $description, 0, 160 ) ) );
}
}, 1 );
Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.
WordPress doesn’t print a meta description, so search engines pick their own snippet from the page. This snippet writes one from content you already have.
On single posts and pages, the description is the excerpt, or the first 28 words of the content if there’s no excerpt. The homepage uses your tagline from Settings → General, and category and tag pages use their description.
Whitespace is tidied and the text is cut at 160 characters, around the length Google shows. If an SEO plugin is active, the snippet does nothing.
View a post’s source and search for name="description".