the_excerpt()
Displays the excerpt (quote) of the post, with [...] at the end (but this is not a link to reading the full material).
If the "excerpt" field is not specified for the post (you specify it on edit post screen), the function "will create" a quote by itself, by cutting the initial part of the post content (the first 55 words of the content will be taken). HTML tags or images will be pre-cut, so they will not be displayed and taken into account when counting.
This function must be used inside WordPress Loop.
Note: If the current post is an attachment (usually displayed in a loop of template files: attachment.php and image.php), the_excerpt() will output the text specified in the "description" (Caption) field and the text will not have [...] at the end of the construction.
the_excerpt() and the_content()
Sometimes it's better to use the_content() because it understands the tag <!--more--> specified in the post content and displays the text above this tag.
Hooks from the function
Returns
null. Nothing (null). Displays a short text.
Usage
<?php the_excerpt(); ?>
Examples
#1 Basic usage
Get a post "Quote" on archive pages (categories, tags, authors, dates):
<?php the_excerpt(); ?>
#2 Changing the length of the cropped text
By default, the length of the excerpt text is 55 words, to change this parameter, you can use the excerpt_length filter. Place next code in the functions.php theme file:
add_filter( 'excerpt_length', function(){
return 20;
} ); #3 Use with conditional tags
Let's check if this page is a category page, if so, replace the_content() with the_excerpt():
if ( is_category() ) {
the_excerpt();
}
else {
the_content();
} #4 Remove [...] construction at the end
By default, if the text is truncated, [...] added at the end. We can change [...] through the excerpt_more filter. Add this code to the functions.php theme file:
add_filter('excerpt_more', function($more) {
return '...';
}); #5 Creation of a link "Read more..." at the end
Again, let's use excerpt_more filter. Copy and paste next code into the functions.php theme file:
add_filter( 'excerpt_more', 'new_excerpt_more' );
function new_excerpt_more( $more ){
global $post;
return '<a href="'. get_permalink($post) . '">Read more...</a>';
}
Changelog
| Since 0.71 | Introduced. |
the_excerpt() the excerpt code WP 6.9
function the_excerpt() {
/**
* Filters the displayed post excerpt.
*
* @since 0.71
*
* @see get_the_excerpt()
*
* @param string $post_excerpt The post excerpt.
*/
echo apply_filters( 'the_excerpt', get_the_excerpt() );
}