Sep 6, 2016

Get the Excerpt by Post ID in WordPress

The get_the_excerpt() entry in the WordPress Codex says that it returns “…either a user-supplied excerpt, that is returned unchanged, or an automatically generated word-counted trimmed-down version of the full post content” (although the more up-to-date WordPress Developer Resources entry has no such language). I find that calling get_the_excerpt() doesn’t work when a post has post content but not a post excerpt. It just returns an empty string, without trying to trim down the post content to automatically create an excerpt as the Codex description would lead you to believe.

The function below can be used to get the excerpt for a post, whether it has a post excerpt already, or it has to generate one using the post content. You can limit the number of words in the excerpt by passing in a $num_of_words argument.

/**
 * 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 );
}