Meta description from the excerpt
Posts and pages get a meta description from their excerpt (or the first words of the text), so search results show a summary you control. Skipped when an SEO plugin is active.
<?php
add_action(
'wp_head',
static function () {
if ( ! is_singular() || defined( 'WPSEO_VERSION' ) || defined( 'RANK_MATH_VERSION' ) || defined( 'AIOSEO_VERSION' ) || defined( 'SEOPRESS_VERSION' ) || class_exists( 'The_SEO_Framework\\Load' ) ) {
return;
}
$post = get_queried_object();
$text = has_excerpt( $post ) ? $post->post_excerpt : wp_trim_words( strip_shortcodes( $post->post_content ), 30, '…' );
$text = trim( preg_replace( '/\s+/', ' ', wp_strip_all_tags( $text ) ) );
if ( '' !== $text ) {
echo '<meta name="description" content="' . esc_attr( mb_substr( $text, 0, 160 ) ) . '">' . "\n";
}
},
1
);
In these packs
- SEO basics: Meta descriptions, social sharing tags, article structured data and cleaner indexing, for sites without an SEO plugin.