The the_excerpt WordPress PHP filter allows you to modify the displayed post excerpt.
Usage
add_filter( 'the_excerpt', 'your_custom_function' );
function your_custom_function( $post_excerpt ) {
// your custom code here
return $post_excerpt;
}
Parameters
$post_excerpt(string): The post excerpt that needs to be modified.
More information
See WordPress Developer Resources: the_excerpt
Examples
Limit Excerpt Length
Limit the post excerpt length to 20 words.
add_filter( 'the_excerpt', 'custom_excerpt_length' );
function custom_excerpt_length( $post_excerpt ) {
$limit = 20;
$words = explode( ' ', $post_excerpt, $limit + 1 );
if ( count( $words ) > $limit ) {
array_pop( $words );
$post_excerpt = implode( ' ', $words ) . '...';
}
return $post_excerpt;
}
Add “Read More” Link
Add a “Read More” link at the end of the post excerpt.
add_filter( 'the_excerpt', 'add_read_more_link' );
function add_read_more_link( $post_excerpt ) {
global $post;
$read_more = ' <a href="' . get_permalink( $post->ID ) . '">Read More</a>';
$post_excerpt .= $read_more;
return $post_excerpt;
}
Remove HTML Tags
Strip all HTML tags from the post excerpt.
add_filter( 'the_excerpt', 'remove_html_tags' );
function remove_html_tags( $post_excerpt ) {
$post_excerpt = strip_tags( $post_excerpt );
return $post_excerpt;
}
Add Custom Prefix
Add a custom prefix to the post excerpt.
add_filter( 'the_excerpt', 'add_custom_prefix' );
function add_custom_prefix( $post_excerpt ) {
$prefix = 'Summary: ';
$post_excerpt = $prefix . $post_excerpt;
return $post_excerpt;
}
Uppercase Excerpt
Convert the post excerpt to uppercase.
add_filter( 'the_excerpt', 'uppercase_excerpt' );
function uppercase_excerpt( $post_excerpt ) {
$post_excerpt = strtoupper( $post_excerpt );
return $post_excerpt;
}