Skip to main content

Outputting a Post Excerpt : WordPress Code Snippet

A simple helper function that I use in most WordPress websites to output a short description or summary of a post. This will use the post excerpt content in full if it has been defined for the post, or return a specific number of words from the main content.

Add the following to your functions.php file:

 * Gets an excerpt from or post or creates one if it is empty
 * @param WP_Post $post
 * @paran int $word_count
 * @return string

function get_post_excerpt( $post, $word_count = 40 )
    if ( false === empty( $post->post_excerpt ) ) {
        return $post->post_excerpt;

    return wp_trim_words( $post->post_content, $word_count );

Usage within your template file:

// Where $post has already been defined and is available as a WP_Post object
$excerpt = get_post_excerpt( $post, 30 );

echo $excerpt;