-
-
Save palimadra/3023928 to your computer and use it in GitHub Desktop.
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'); |
What would be the exact markup code for this and do I put this in the head:
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 "";
}
add_action('wp_head', 'create_meta_desc');
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 .
function create_meta_desc() {
global $post;
if (!is_singular()) {return; }
elseif(!empty( $post->post_excerpt)) {
echo "<meta name='description' content='$post->post_excerpt' />";
}
else{
$meta = apply_filters('the_content', $post->post_content);
$meta = strip_tags($meta);
$meta = strip_shortcodes($meta );
$meta = str_replace(array("\n", "\r", "\t"), ' ', $meta);
$meta = substr($meta, 0, 400);
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 );
Also, Can I use your code with this plugin to allow me to have automatically generated meta description from content?
Please see this plugin: https://en-ca.wordpress.org/plugins/head-meta-data/
Can I use your code in this plugin you think?