Auto Generate Meta Description from Content using PHP
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