Created
June 30, 2012 14:26
-
-
Save palimadra/3023928 to your computer and use it in GitHub Desktop.
WordPress - Automatically generate meta description from content
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); |
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
This is a really handy gist! I made some modifications to allow it to use the post_excerpt for a meta description if it existed, and generate a description for posts types without an excerpt, such as pages.
I also always have problems with strip_shortcodes() stripping out all my content, so I ran the content filter before strip_tags and strip_shortcodes .