Using WordPress ‘get_the_excerpt()’ PHP function

The get_the_excerpt() WordPress PHP function retrieves the post excerpt.

Usage

echo get_the_excerpt($post);

Parameters

  • $post (int|WP_Post) (Optional) Post ID or WP_Post object. Default is global $post. Default: null

More information

See WordPress Developer Resources: get_the_excerpt()

Examples

Display Post Excerpt

Display the excerpt of a post:

echo get_the_excerpt();

Use Excerpt for HTML Meta Description

Add this code snippet in the head section of your theme to use the post excerpt as the meta description for single post pages:

<meta name="description" content="<?php echo wp_strip_all_tags(get_the_excerpt(), true); ?>" />

Limit Manual Excerpt Display

To limit the displayed manual excerpt to 260 characters and truncate after the last word, place this code snippet in your theme where the_excerpt() is located:

$excerpt = get_the_excerpt();
$excerpt = substr($excerpt, 0, 260);
$result = substr($excerpt, 0, strrpos($excerpt, ' '));
echo $result;

Prevent Notice with has_excerpt()

To prevent a Notice: Undefined offset: -1 in post-template.php, use has_excerpt():

$excerpt = '';
if (has_excerpt()) {
    $excerpt = wp_strip_all_tags(get_the_excerpt());
}

Expandable Excerpt Function

Add this expandable_excerpt function to your functions.php file to create an expandable excerpt:

function expandable_excerpt($excerpt) {
    $split = explode(" ", $excerpt);
    $len = count($split);
    $words_to_show_first = 19;

    if ($len > $words_to_show_first) {
        $firsthalf = array_slice($split, 0, $words_to_show_first);
        $secondhalf = array_slice($split, $words_to_show_first, $len - 1);
        $output = '<p class="event-excerpt" >';
        $output .= implode(' ', $firsthalf) . '<span class="see-more">';
        $output .= implode(' ', $secondhalf) . '</span></p>';
        return $output;
    } else {
        return $excerpt;
    }
}

To use the expandable_excerpt function, replace get_the_excerpt() with expandable_excerpt(get_the_excerpt()) in your theme:

echo expandable_excerpt(get_the_excerpt());