Forcing a ‘read more’ link on WordPress excerpts even when excerpt text is set

Wow, that title is a bit of a mouthful. OK, so let me decipher: you can customise WordPress excerpts to add a “read more” link to post excerpts, e.g. as per this (cleaned up) example from the codex:

function new_excerpt_more( $more ) {
	global $post;
	return '<a class="moretag" href="'. get_permalink( $post->ID ) . '">Read the full article...</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );

But… this will not add a more link if you have explicitly set a custom excerpt on a post. The excerpt_more filter is only called by wp_trim_excerpt() where $text is not provided. Sometimes, this behaviour is undesirable, e.g. you may set excerpt text because the auto-generated excerpt is inappropriate, but still want the click through ‘read more’ link.

To get round this, we need to apply a filter to wp_trim_excerpt, which is called later in the function, but first we need to strip the default excerpt_more behaviour so that we don’t end up with e.g. duplicate … or similar:

add_filter( 'excerpt_more', function ( $more ) { return ''; } );

function custom_excerpt_filter( $text, $raw_excerpt ) {
	global $post;
	return $text . '… <a class="read-more" href="'. get_permalink( $post->ID ) . '">read more »</a>';
}
add_filter( 'wp_trim_excerpt', 'custom_excerpt_filter', 10, 2 );

Tada, a working “read more” link on all excerpts irrelevant of length or provided custom excerpt text.

Please note: if you are silly, and running < PHP 5.3 you will need to replace the “inline” (lambda) function on the excerpt_more filter with:

function new_excerpt_more( $more ) { return ''; }
add_filter( 'excerpt_more', 'new_excerpt_more' );
affiliate window advert

Leave a Comment

Please read the comment policy before leaving a comment.