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
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.