Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.