The_excerpt() Function in WordPress: Implementation, Length

The the_excerpt() function in WordPress is commonly used to display a brief summary or excerpt of a post. It is particularly useful in situations where you want to show a condensed version of the post content, such as on archive pages or in a list of posts.

Default Implementation

By simply calling the_excerpt() within the loop in your template file, WordPress will automatically generate an excerpt for each post based on the post content. This default behavior limits the excerpt length to 55 words by default, but this can be customized using filters.

<?php if(has_excerpt()) { ?>
	<div class="excerpt"><?php the_excerpt(); ?></div>
<?php } ?>

Or an option using the get_the_excerpt() function:

<?php $excerpt = get_the_excerpt(); 
if ($excerpt) { ?>
	<div class="excerpt"><?php echo $excerpt; ?></div>
<?php } ?>

Custom Excerpt Length

To control the length of the excerpt displayed, you can use the excerpt_length filter. For example, you can add the following code to your theme’s functions.php file to set a custom excerpt length of 10 words:

function custom_excerpt_length( $length ) {
    return 10;
}
add_filter( 'excerpt_length', 'custom_excerpt_length' );

Or such an option using the wp_trim_words() function:

$excerpt = wp_trim_words( get_the_excerpt(), 10, '...' );
echo $excerpt;

This code snippet will output excerpt with a clipping of up to 10 words.

Excerpt from the post by ID

This code snippet will allow you to output an excerpt from the post by ID using the has_excerpt() function:

<?php $post_id = 1;
if (has_excerpt( $post_id )) { ?>
	<div class="excerpt"><?php echo get_the_excerpt( $post_id ); ?></div>
<?php } ?>