Snippet: Wordpress - Customise the Excerpt Length and More string

These functions and hooks let you customise the output of the_excerpt() template tag. Just copy and paste into the functions.php file in your theme. This works for both posts and pages.

To change the excerpt length (how many words are output - the default is 55 words) , define a function which returns the number you want and then call it with add_filter() on the excerpt_length filter as shown below.

function custom_excerpt_length($length)
return 20;
add_filter('excerpt_length', 'custom_excerpt_length');

By default excerpts which are generated by Wordpress (as opposed to defined via the "Excerpt" box) have the string "[...]" You might want to turn this into a link to the post or page and/or change the dots to something like "more". The code below does both of these things using str_replace().

function custom_excerpt_more($more)
global $post;
return str_replace('[...]', '<a href="'.get_permalink($post-&gt;ID).'"> more...</a>', $more);
add_filter('excerpt_more', 'custom_excerpt_more');

You can change the second parameter of str_replace() to whatever you want to be displayed. I included the $post global so that I could get the permalink and make the string into a link to the post/page.

Please note these will not work if you have any plugin installed which removes the excerpt hooks. One such plugin is the Event Calendar 3 plugin. If you come across any more please let me know in the comments.

A Note on Snippets: When customising a CMS such as Wordpress it is often the simplest pieces of code which are the hardest to either find or remember. These snippets are placed here for my own reference and will hopefully be useful to others. If you find them useful or have any suggestions, please let me know.