SEO PHP Beginner

Add Meta Descriptions Without an SEO Plugin

Print a meta description on every post and page from its excerpt, and on the homepage from your tagline.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 20 lines
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 );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

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.

Don't use with Yoast SEO, Rank Math, Slim SEO, SEOPress, All in One SEO. Check the notes below before adding it.

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.

How it works

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.

Things to watch

  • Write excerpts for important pages. Automatic descriptions from the first paragraph are often not the best summary.
  • Google may still choose its own snippet if it thinks another part of the page answers the search better.

How to test it

View a post’s source and search for name="description".

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only