Last active
February 5, 2018 14:58
-
-
Save timothyjensen/18571c390398d8b3b779033c65357a00 to your computer and use it in GitHub Desktop.
Get an auto generated post excerpt, or a manual excerpt if one has been set.
This file contains hidden or 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 | |
// Make sure to prefix the function if you do not use a namespace. | |
// namespace TimJensen\HelperFunctions; | |
/** | |
* Returns an auto generated post excerpt, or a manual excerpt if one has been set. | |
* | |
* @version 1.2.1 | |
* | |
* @param int $post_id Required. Post ID. | |
* @param mixed $excerpt_length Optional. Length of the automatic except. | |
* Does not affect the manual excerpt length. Defaults to 55. | |
* @param mixed $excerpt_more Optional. Text that appends the excerpt. Defaults to '...'. | |
* @param bool $more_link Optional. Includes a link to the singular post. Defaults to true. | |
* | |
* @return string | |
*/ | |
function get_post_excerpt( $post_id, $excerpt_length = null, $excerpt_more = null, $more_link = true ) { | |
$post = get_post( $post_id ); | |
if ( null === $excerpt_length ) { | |
$excerpt_length = apply_filters( 'excerpt_length', 55 ); | |
} | |
if ( $post->post_excerpt ) { | |
$excerpt = $post->post_excerpt; | |
} else { | |
$excerpt = strip_shortcodes( $post->post_content ); | |
$excerpt = apply_filters( 'the_content', $excerpt ); | |
$excerpt = str_replace( ']]>', ']]>', $excerpt ); | |
$original_word_count = str_word_count( strip_tags( $excerpt ) ); | |
$excerpt = wp_trim_words( $excerpt, $excerpt_length, '' ); | |
$is_trimmed_excerpt = str_word_count( $excerpt ) < $original_word_count; | |
} | |
if ( null === $excerpt_more ) { | |
$excerpt_more = apply_filters( 'excerpt_more', '…' ); | |
} | |
// Remove the excerpt more (i.e., '...') when there is no more text to show. | |
$excerpt_more = empty( $is_trimmed_excerpt ) ? '' : $excerpt_more; | |
$excerpt = apply_filters( 'get_post_excerpt_excerpt', $excerpt . $excerpt_more ); | |
if ( false === $more_link ) { | |
return $excerpt; | |
} else { | |
$more_link = sprintf( '<a href="%s" class="more-link read-more-link">%s</a>', | |
get_the_permalink( $post->ID ), | |
apply_filters( 'get_post_excerpt_read_more_text', 'Read More' ) | |
); | |
} | |
return $excerpt . apply_filters( 'get_post_excerpt_read_more_link', $more_link ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment