the_excerpt() is a core WordPress function used to output a post's excerpt. Its primary function is to retrieve and display the excerpt for the current post. If no manual excerpt is set, it automatically extracts the first 55 words from the post content and appends [...] by default. This function must be used within the WordPress main loop.
Function Description & Basic Usage
The basic call is simple:
<?php the_excerpt(); ?>
This code directly outputs the current post's excerpt. If no manual excerpt is set, WordPress generates one automatically.
Customizing Excerpt Length
The default 55 words may not suit all themes. You can modify the length using the excerpt_length filter. This example sets it to 150 words:
function custom_excerpt_length($length) {
return 150;
}
add_filter('excerpt_length', 'custom_excerpt_length');
Note: This filter controls the word count, not character count. For mixed-language content, words are separated by spaces.
Customizing the Excerpt More Indicator
The default [...] can be modified in two ways.
1. Replace with Plain Text
Use the excerpt_more filter to replace [...] with other text, like ... or 'Continue reading':
function custom_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');
2. Add a 'Read More' Link
A common practice is to add a link to the full post:
function custom_excerpt_more_link($more) {
global $post;
return ' <a href="' . get_permalink($post->ID) . '" class="read-more">Read More</a>';
}
add_filter('excerpt_more', 'custom_excerpt_more_link');
This adds a link with a read-more CSS class for easy styling.
Important Notes & Best Practices
- Use Within the Loop:
the_excerpt()must only be called inside the main WordPress loop. - Manual Excerpt Priority: Content entered in the post editor's 'Excerpt' box completely overrides auto-generated content.
- Code Placement: All custom functions should be added to your theme's
functions.phpfile. - Function Location: The
the_excerpt()function is defined in the core filewp-includes/post-template.php.
Extension: Retrieve Excerpt Text (Without Output)
To get the excerpt as a string for further processing (e.g., storing in a variable), use get_the_excerpt():
$my_excerpt = get_the_excerpt($post_id); // Post ID can be specified
// You can now process $my_excerpt
By using these methods and filters, you can fully control how WordPress post excerpts are displayed to match your site's design and user experience.