Created
September 6, 2016 18:13
-
-
Save kellenmace/6209d5f1e465cdcc800e690b472f8f16 to your computer and use it in GitHub Desktop.
Get the Excerpt by Post ID in WordPress
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 | |
/** | |
* Return the post excerpt, if one is set, else generate it using the | |
* post content. If original text exceeds $num_of_words, the text is | |
* trimmed and an ellipsis (…) is added to the end. | |
* | |
* @param int|string|WP_Post $post_id Post ID or object. Default is current post. | |
* @param int $num_words Number of words. Default is 55. | |
* @return string The generated excerpt. | |
*/ | |
function km_get_the_excerpt( $post_id = null, $num_words = 55 ) { | |
$post = $post_id ? get_post( $post_id ) : get_post( get_the_ID() ); | |
$text = get_the_excerpt( $post ); | |
if ( ! $text ) { | |
$text = get_post_field( 'post_content', $post ); | |
} | |
$generated_excerpt = wp_trim_words( $text, $num_words ); | |
return apply_filters( 'get_the_excerpt', $generated_excerpt, $post ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment