WP Assist
  1. Home
  2. Snippets

[How To] Generate Description from Content

WPAssist // (Updated: )

If you want to generate descriptions meta from post content automatically, you can use the following snippet.
Short and sweet:

$description = wp_trim_words( esc_attr( strip_shortcodes( strip_tags( get_the_content() ) ) ), 15, '...' );

If you need a function wrapper:

function wpa_get_description( $words_count = 15, $ellipsis = "..." ){
  if( has_excerpt() ){
    return apply_filters( 'meta_description', get_the_excerpt() );
  } else {
    return apply_filters( 'meta_description', wp_trim_words( esc_attr( strip_shortcodes( strip_tags( get_the_content() ) ) ), $words_count, $ellipsis ) );
  }
}

You can use this wrapper like this:

$description = wpa_get_description();

Description of Functions Used

wp_trim_words – Trims text using word count and appends an ellipsis at the end
esc_attr – Escape special characters in text to make it work in html attributes
strip_shortcodes – Strips all shortcodes from the text
strip_tags – Strips html tags from the text
get_the_content – Gets content of current post

Leave a Reply

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

Share Share Tweet