Link Featured Images to Their Posts
Wraps featured images on blog, archive and search pages in a link to the post, for themes that show the image without one. Works with classic themes and the Featured Image block.
Opens WPIDE on
Code
// The image link repeats the title link, so it is hidden from screen readers and skipped by the Tab key.
$wpide_featured_link_open = function ( $post_id ) {
return '<a href="' . esc_url( get_permalink( $post_id ) ) . '" class="wpide-featured-image-link" aria-hidden="true" tabindex="-1">';
};
$wpide_featured_link_skip = function ( $post_id ) {
return ! $post_id || is_admin() || is_feed() || ( is_singular() && (int) $post_id === get_queried_object_id() );
};
// Classic themes: the_post_thumbnail() and get_the_post_thumbnail().
add_filter( 'post_thumbnail_html', function ( $html, $post_id ) use ( $wpide_featured_link_open, $wpide_featured_link_skip ) {
if ( '' === trim( (string) $html ) || wp_is_block_theme() || false !== stripos( $html, '<a ' ) || $wpide_featured_link_skip( $post_id ) ) {
return $html;
}
return $wpide_featured_link_open( $post_id ) . $html . '</a>';
}, 10, 2 );
// Block themes: the Featured Image block when "Link to post" is switched off.
add_filter( 'render_block_core/post-featured-image', function ( $content, $block, $instance = null ) use ( $wpide_featured_link_open, $wpide_featured_link_skip ) {
$post_id = ( $instance instanceof WP_Block && ! empty( $instance->context['postId'] ) ) ? (int) $instance->context['postId'] : 0;
if ( '' === trim( (string) $content ) || ! empty( $block['attrs']['isLink'] ) || false !== stripos( $content, '<a ' ) || $wpide_featured_link_skip( $post_id ) ) {
return $content;
}
return preg_replace_callback( '/<img\b[^>]*>/i', function ( $match ) use ( $wpide_featured_link_open, $post_id ) {
return $wpide_featured_link_open( $post_id ) . $match[0] . '</a>';
}, $content, 1 );
}, 10, 3 );
Notes
Images that already have a link are left alone, including Featured Image blocks with "Link to post" switched on. If a classic theme puts its own link around the image from outside, turn this off to avoid a link inside a link. The extra link is hidden from screen readers and the Tab key because the post title already links to the same page.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.