How to: make the whole WordPress excerpt clickable

A client recently asked me to make the post excerpts in their blog page clickable. This seems like a reasonable request and the logical answer (if you know your WordPress basics) is to open the relevant template file (probably index.php or home.php in this case) and wrap the_excerpt(); in <a href="<?php the_permalink(); ?>".. (and so on).

Except there’s two problems with this method:

  1. WordPress formats the excerpt and wraps it in <p> tags
    Which means that you’re then wrapping your block level <p> in an inline <a>. I’m sure some of you either don’t know what this means or don’t care, but I do. Let’s call it nostalgia for the days of carefully ensuring the mark-up on every page was W3C compliant. ;)
  2. Links, which are allowed in an excerpt, break your code
    If you have a link in your excerpt, which is allowed in WordPress, the link in the excerpt will break the link wrapped around the excerpt. You then end up with things linked that you don’t want to be linked and things that you do want to be linked, not. Or something.

Solution one: add_filter()

There is a simple solution that makes use of the built in excerpt filter, allowing you to wrap the excerpt in a link before it gets marked-up, solving problem 1:

function clickable_excerpt( $excerpt ) {
	return '<a href="'. get_the_permalink() .'" class="excerpt">'. $excerpt .'</a>';
}
add_filter( 'get_the_excerpt', 'clickable_excerpt' );

(This is ideally placed in your theme functions.php file)

Solution two: add_filter() & strip_tags()

The only thing is this *doesn’t* solve problem 2. The effects of the broken link mark-up are less disastrous with this method, but not removed altogether. The simplest (dirtiest) solution to this, aside from not using links in your excerpts at all, is to remove HTML from the excerpt altogether:

function clickable_excerpt( $excerpt ) {
	return '<a href="'. get_the_permalink() .'" class="excerpt">'. strip_tags( $excerpt ) .'</a>';
}
add_filter( 'get_the_excerpt', 'clickable_excerpt' );

Bob’s your uncle: clickable WordPress excerpts without the invalid mark-up. :)

6 Comments

  1. Or, if you wanted to leave formatting intact in the excerpt, would be to remove any links from the excerpt?

    function clickable_excerpt( $excerpt ) {
    	return '<a href="'. get_the_permalink() .'">'. preg_replace( '|</?a.*?>|i', '', $excerpt ) .'</a>';
    }
    add_filter( 'get_the_excerpt', 'clickable_excerpt' );

    • Jem

      18 Dec at 1:58 pm

      You’ve just ruined my follow up entry. :P

      • :P Not exactly, as your site has helpfully removed the actual regex that I included – or you have ;)

        • Jem

          18 Dec at 2:01 pm

          You should have used the HTML entity equivalents dear, tut tut. I’ve fixed that for you :p

  2. Thanks for the easy solution.

  3. 2018 and still working (solution 1) thanks very much! It neary saves my job ;)