Skip to content

Instantly share code, notes, and snippets.

@palimadra
Created June 30, 2012 14:26
Show Gist options
  • Save palimadra/3023928 to your computer and use it in GitHub Desktop.
Save palimadra/3023928 to your computer and use it in GitHub Desktop.
WordPress - Automatically generate meta description from content
function create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post->post_content);
$meta = strip_shortcodes($post->post_content);
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 125);
echo "<meta name='description' content='$meta' />";
}
add_action('wp_head', 'create_meta_desc');
@onliniak
Copy link

onliniak commented Aug 24, 2018

Thanks for this gist, but it need little update for people who migrate from classic editor to Gutenberg.

You must add"<!-- wp:paragraph -->", "<p>"to str_replace, in Gutenberg all paragraphs are begining (and ending) with <!-- wp:paragraph --> also sometimes Gutenberg add <p> to html.

// $meta = str_replace( array("\n", "\r", "\t", "<!-- wp:paragraph -->", "<p>", "<!--nextpage-->"), ' ', $meta );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment