I pretty much randomly decide to post WordPress tips whenever I start seeing questions asked repeatedly on the forums. This time around, I’ve been seeing a fair amount of questions pertaining to linking post thumbnails (using the_post_thumbnail) to their post permalink. There are a couple of options here, so let’s see what they are! 

 

Both options are quite simple. The first option we’ll discuss is just dropping a bit of code into your theme’s functions.php file (inside the php tags as always). This bit of code here links all thumbnails you have to their respective post permalink.
 

// THIS LINKS THE THUMBNAIL TO THE POST PERMALINK
add_filter( 'post_thumbnail_html', 'my_post_image_html', 10, 3 );
function my_post_image_html( $html, $post_id, $post_image_id ) {
$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_post_field( 'post_title', $post_id ) ) . '">' . $html . '</a>';
return $html;
}

We also have another option. This one gives a bit more control instead of linking every thumbnail. Instead of editing the functions.php file this time, we edit the appropriate template where the thumbnail is coded; single.php, index.php, loop.php for instance. You would already have code similar to this in your template:

<?php
// original thumbnail code
the_post_thumbnail();
?>

So we just need to add the link to it which is simply:

<a href="<?php the_permalink(); ?>">
<?php
// thumbnail code simply wrapped in a link
the_post_thumbnail();
?>
</a>

Edit: A little update to this post. We probably shouldn’t add links unless the thumbnail exists, so here is a way to do that:

<?php
if ( has_post_thumbnail()) {
  echo '<a href="' . get_permalink($post->ID) . '" >';
  the_post_thumbnail( 'title-image', array( 'class' => 'title-image', 'alt' => 'Title Icon' );
  echo '</a>';
}
?>

That’s it! Two simple options for linking your thumbnails to your permalinks. Hopefully somebody finds this useful!
If anybody has any suggestions, requests, or questions, just drop a comment my way. I’m happy to give an answer. If I don’t know the answer, I will do my very best to find it for you. We can all learn along the way!

css.php
%d bloggers like this: