Change Excerpt Length

This code snippet allows you to change the length of excerpts in WordPress. By default, excerpts display a limited number of words from the post content. With this code, you can customize the number of words displayed in the excerpt.

The code uses the excerpt_length filter to modify the length. It defines an anonymous function that takes the current excerpt length as a parameter ($length). Inside the function, you can set the desired number of words to be displayed in the excerpt by modifying the return statement.

In the provided example, the excerpt length is set to 40 words. You can adjust this value to fit your specific needs.

To change the excerpt length, add this code to your theme’s functions.php file. It will apply the filter with a priority of 500, ensuring it takes effect during the excerpt generation process.

PHP
add_filter(
	'excerpt_length',
	function ( $length ) {
		// Number of words to display in the excerpt.
		return 40;
	},
	500
);