Meta description is one of the most critical elements for on-page SEO. Most of the SEO plugins will generate meta descriptions from your content automatically when a custom meta description is not provided. However, if you want to generate descriptions using PHP, you can use the following snippet to auto generate meta description from content.

One-liner version to generate the description:

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

Custom PHP Function to generate description from post content:

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

Deal Notice: We are using A2 hosting for all of our websites, and we are really happy with their service. So we wanted to share you this discount link for you to try it out. If you get a hosting using this link, you will also help us build better content for you: SSD Hosting - 300% Faster Than Standard Hard Drives