Auto-Generate Meta Description in Yoast

, ,

So Yoast appears to have removed the ability for it to auto-generate the meta description based off of the content of the page or post.  Using this snippet turns Yoast into an automated SEO solution that will pull the first 250 characters of content to use within the Meta Description.  I would say for most pages this is sufficient enough but there are always some pages where you will want to customize it yourself.

/* Works with Yoast to auto-generate the meta description of a page based off of content.
add_filter( 'wpseo_metadesc', 'wpcms_auto_gen_meta_desc' ); 
function wpcms_auto_gen_meta_desc($cur_metadesc) {
  if( trim($cur_metadesc) == '' && !isset($_POST) ) { //if none is set and there is no possibility of post data in content
    global $post;
    $page_content = apply_filters('the_content', $post->post_content); //get current page content
    $new_metadesc = strip_tags( $page_content ); //strip all html
    $new_metadesc = preg_replace( "/\r|\n/", " ", $new_metadesc ); //remove carriage returns
    $new_metadesc = trim($new_metadesc); //remove beginning and ending white spaces
    $new_metadesc = str_replace( "	", " ", $new_metadesc ); //replace tabs with spaces
    $new_metadesc = preg_replace('/\s+/', ' ', $new_metadesc); //replace multiple spaces with a single space
    $new_metadesc = preg_replace('/[\x00-\x1F\x7F-\xFF]/', '', $new_metadesc);//remove any unicode characters
    $new_metadesc = trim(substr($new_metadesc, 0, 250));
    return $new_metadesc;
  } else {
    return $cur_metadesc;




Posted on

August 29, 2018

Submit a Comment

Your email address will not be published. Required fields are marked *