Excerpts aren’t very flexible out of the box with WordPress. That’s why I came up with this nice function for getting the first paragraph of the post content. This makes it so that you don’t have any excerpts that just get randomly cut off in the middle of a sentence.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create a custom excerpt string from the first paragraph of the content. | |
* | |
* @param integer $id The id of the post | |
* @return string $excerpt The excerpt string | |
*/ | |
function wp_first_paragraph_excerpt( $id=null ) { | |
// Set $id to the current post by default | |
if( !$id ) { | |
global $post; | |
$id = get_the_id(); | |
} | |
// Get the post content | |
$content = get_post_field( 'post_content', $id ); | |
$content = apply_filters( 'the_content', strip_shortcodes( $content ) ); | |
// Remove all tags, except paragraphs | |
$excerpt = strip_tags( $content, '<p></p>' ); | |
// Remove empty paragraph tags | |
$excerpt = force_balance_tags( $excerpt ); | |
$excerpt = preg_replace( '#<p>\s*+(<br\s*/*>)?\s*</p>#i', '', $excerpt ); | |
$excerpt = preg_replace( '~\s?<p>(\s| )+</p>\s?~', '', $excerpt ); | |
// Get the first paragraph | |
$excerpt = substr( $excerpt, 0, strpos( $excerpt, '</p>' ) + 4 ); | |
// Remove remaining paragraph tags | |
$excerpt = strip_tags( $excerpt ); | |
return $excerpt; | |
} |