Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kellenmace/6209d5f1e465cdcc800e690b472f8f16 to your computer and use it in GitHub Desktop.
Save kellenmace/6209d5f1e465cdcc800e690b472f8f16 to your computer and use it in GitHub Desktop.
Get the Excerpt by Post ID in WordPress
<?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