Too lazy to add meta description to your articles? Then, why not automatically generate a meta description from your WordPress post by striping out all shortcodes and tags? Here’s how to do it.
Instructions:
Add this code to your theme’s functions.php file or in a site-specific plugin. Make sure you have wp_head(); ?> in the header.php of your wordpress theme or this snippet will not work.
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');
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: Best WordPress Page Builders (Compared).
As already mentioned (no clue why the author is not updating his mistake) strip/replace this code part: $meta = strip_shortcodes($post->post_content); with just: $meta = strip_shortcodes($meta); else it has no sence and is incorrect and looks terrible on google!
Wow,. that broke my site. As soon as you put it in the header you get an error code so it doesn’t work. Too bad as it’s exactly what I needed 🙁
what is the error you get?
substr() will create invalid UTF-8. Use mb_substr() instead
// add meta description tag
function wcs_add_meta_description_tag() {
global $post;
if ( is_single() ) {
$meta = strip_tags( $post->post_content );
$meta = strip_shortcodes( $post->post_content );
$meta = str_replace( array(“\n”, “\r”, “\t”), ‘ ‘, $meta );
$meta = mb_substr( $meta, 0, 125, ‘utf8’ );
echo ” . “\n”;
}
}
add_action( ‘wp_head’, ‘wcs_add_meta_description_tag’ , 2 );
Would you think possible to take H2 content from a post, limit the numbers of characters or word, and copy it into the description by default? Thanks!
Sorry Pal, but here’s a correction on this algorithm:
function create_meta_desc() {
global $post;
if (!is_single()) { return; }
$meta = strip_tags($post->post_content);
$meta = strip_shortcodes($meta); /* here you have to use the same variable, or else the strip_tags will not have any effect */
$meta = str_replace(array(“n”, “r”, “t”), ‘ ‘, $meta);
$meta = substr($meta, 0, 125);
echo “”;
}
add_action(‘wp_head’, ‘create_meta_desc’);
[…] [Source: WpSnipp] […]
have HTML TAGS !
I’m not sure what you mean? however HTML tags are stripped out using “strip_tags”
no it isn’t. i had to add a strip_tags right before the substr() function, that worked