I am developing a custom WordPress theme and I want to dynamically generate the meta description tag based on the post content.

Currently I am trying to output the description inside header.php using the post excerpt.

Example code:

<?php $description = get_the_excerpt(); echo '<meta name="description" content="' . esc_attr($description) . '">'; ?>

This works correctly when the post has an excerpt. However, on some pages the excerpt is empty, which results in an empty or missing meta description tag.

My goal is to always generate a meta description automatically for SEO purposes.

What is the recommended approach in WordPress when an excerpt is not available?

For example:

Should I fallback to get_the_content() and trim it to a specific character limit? Is there a built-in WordPress function or best practice for generating a fallback meta description?

I would like to implement a clean solution inside a custom theme without relying on an SEO plugin.

Riseon Ads's user avatar

New contributor

Riseon Ads is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

4

Unless you are going to use AI, your idea is valid. Use wp_trim_words either on get_the_excerpt or on get_the_content whichever not empty.

function get_short_description($limit = 30) { $content = has_excerpt() ? get_the_excerpt() : get_the_content(); return wp_trim_words($content, $limit, '...'); }

Please note on some theme builders and plugins, the actual content might be inside custom fields or meta values. Depends on the theme or plugin.

IT goldman's user avatar

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.