Skip to content

Instantly share code, notes, and snippets.

@kjbrum
Last active April 16, 2020 12:08
Show Gist options
  • Save kjbrum/8f455fa285607dabbcf5 to your computer and use it in GitHub Desktop.
Save kjbrum/8f455fa285607dabbcf5 to your computer and use it in GitHub Desktop.
Create a custom excerpt from the first paragraph of the content.
<?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|&nbsp;)+</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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment