Link Post Permalink To Post Thumbnail

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.

Noor Mustafa Raza

Noor Mustafa Raza

I am a WordPress Developer and Designer, author @WPArena. I am providing Free WordPress consultation and can help you to install WordPress in a secure way to small businesses and bloggers.

Join the Conversation

2 Comments

  1. Could you please explain more, where should write this code to make it happen ?

    1. 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

Leave a comment

Your email address will not be published. Required fields are marked *