Add Links to Featured Images in WordPress Programmatically

Normally, you would output a featured image (a.k.a post thumbnail) in WordPress like this:

if ( has_post_thumbnail() ) {

Featured images are most commonly used to display an image alongside the excerpt for a post on a blog page. If your theme doesn’t link the featured images to the post, you can use this code to programmatically add the links:

* Wrap featured images in anchor tags that point back to the original post
add_filter( 'post_thumbnail_html', function ( $html, $post_id ) {
return sprintf(
'<a title="%s" href="%s">%s</a>',
esc_url( get_permalink( $post_id ) ),
esc_attr( get_post_field( 'post_title', $post_id ) ),
}, 10, 2 );

Now, adding the normal code for displaying a featured image will also wrap the image in a link.

Note: This will change the output for the image markup everywhere that featured images may be used. If there are contexts where you don’t want this functionality, be sure to conditionally change the markup if possible. Otherwise, you will probably be best off modifying the theme’s markup manually.


    1. Jerome,

      Yes, you can add the code there and it will work, but it isn’t a best practice. The reason for this is that if you put it in the theme and your theme has an update, updating the theme will cause you to lose any customizations you’ve made. The best thing to do is to create a custom plugin for your site or make sure you are running a child theme and only make edits in that child theme.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.