WordPress Custom Excerpt Length and Read More Link

WordPress cuts the automatic excerpt at 55 words and adds […]. This snippet changes both: it makes the excerpt 15 words long and adds a “Read more” link to the post. Put it in the functions.php of your theme, or in a plugin.

// 1. Excerpt length in words
add_filter( 'excerpt_length', function () {
	return 15;
}, 999 ); // a high priority, so it wins over the theme

// 2. The text after the excerpt
add_filter( 'excerpt_more', function () {
	return '&hellip; <a class="read-more" href="' . esc_url( get_permalink() ) . '">Read more</a>';
} );

Test it

We make a post with a long text and ask for its excerpt:

$id = wp_insert_post( array(
	'post_title'   => 'A long post',
	'post_status'  => 'publish',
	'post_content' => 'WordPress is a free and open source content management system. It is written in PHP and uses a database. You can build a blog, a business site or an online store with it, and extend it with plugins and themes.',
) );
global $post;
$post = get_post( $id );
setup_postdata( $post );
echo get_the_excerpt( $post );
wp_reset_postdata();
Output

WordPress is a free and open source content management system. It is written in PHP&hellip; <a class="read-more" href="http://example.com/a-long-post/">Read more</a>

The excerpt has 15 words and the link. Use the_excerpt() in your template to print it. If a post has a hand written excerpt, WordPress uses it as it is, and the filters do not change it.

Related: How to limit WordPress post content length?


Learn more about the similar topics:
Tutorials
WordPress Themes
WordPress Top Theme List
WordPress Theme Files and Functions
WordPress Template Hierarchy
WordPress Enqueue Scripts and Styles
WordPress Loop
WordPress WP_Query Class
Exercises & Assignments
Build and activate a minimal classic theme
Show the three latest posts with WP_Query
Load a stylesheet with wp_enqueue_style and a version
Show a message only on the front page
Create a child theme which changes the footer
Interview Questions & Answers
What is a WordPress theme?
What are commonly used WordPress theme functions?
Which function is used to get the home URL in WordPress?
Which are the necessary files for a WordPress theme?
What is the use of the wp_head() function in WordPress?
What is the WordPress Loop?
What is the difference between is_home() and is_front_page()?