How To Link Post Thumbnail To The Post Permalink

Are you looking for a way to link your Post Thumbnail to Post Permalink? Then, this guide is a definite for you. The issue came when I was looking for a way to show the thumbnail with post permalink. And I found a solution on WordPress but it was not satisfying me. So I tried the below-given code to the functions.php of  WordPress theme and It automatically linked all post thumbnails to the post permalink.

add_filter( 'post_thumbnail_html', 'wps_post_thumbnail', 10, 3 );
function wps_post_thumbnail( $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;
}

You 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>';
}
?>

Hope, the above code snippets will cater your needs of linking Post Thumbnails to Permalinks. If there comes any issues, please don’t hesitate to ask in the comments section below.

2 thoughts on “How To Link Post Thumbnail To The Post Permalink”

    • Hi AbdulAziz,

      Thanks for the comment. You can put this code in your functions.php. Please note, before making any changes, backup the file. Don’t try to do it, if you don’t know how to upload theme files using cPanel.
      Thanks

      Reply

Leave a Comment