Get the First Paragraph as an Excerpt for WordPress

WordPress by default will generate the auto excerpt from the content with 55 words and if the amount is greater than that, then the string ‘[…]’ will be appended to the excerpt. If the string is less than 55 words, then the content will be returned as-is. In other cases, if manual excerpt was added to the post, it will be used as-is instead of creating the 55 words.

Instead of creating manual excerpts, using the first paragraph for each content as an excerpt will be a great idea. This is a piece of code cheese for your theme functions.php to get the first paragraph from the post content.

add_filter( 'wp_trim_excerpt', 'my_custom_excerpt', 10, 2 );

function my_custom_excerpt($text, $raw_excerpt) {
    if( ! $raw_excerpt ) {
        $content = apply_filters( 'the_content', get_the_content() );
        $text = substr( $content, 0, strpos( $content, '</p>' ) + 4 );
    return $text;

The function above adding a filter to modify the wp_trim_excerpt returned value by checking for the manual excerpt. If a manual excerpt was not provided, then the first paragraph from the post content will be returned as a result. There will be no 55 words or ‘[…]’ in the excerpt.

But the function also processes all shortcodes found in the first paragraph too? Using strip_shortcodes() function will remove the shortcodes. Replace line 5 with the code below:

$content = apply_filters( 'the_content', strip_shortcodes( get_the_content() ) );

But I want to remove images from it? We can do it with preg_replace using a pattern. Add new line after line 7 with this :

$text = preg_replace("/<img[^>]+\>/i", "", $text); 

Now we have the first paragraph without shortcodes or images. Happy coding!