WordPress: How to link inline post images to the single post page

My client’s landing page shows their blogroll. The first image you see on the site is the first image in their latest post. Their images are always linked to the image file by default. I’ve found a solution to change that default to link to none, but for past posts this isn’t a good fix.

I’ve found this code which removes links to images from the post content:

Read More
add_filter( 'the_content', 'attachment_image_link_remove_filter' );
function attachment_image_link_remove_filter( $content ) { 
    $content = preg_replace( array('{<a(.*?)(wp-att|wp-content/uploads)[^>]*><img}', '{ wp-image-[0-9]*" /></a>}'), array('<img','" />'), $content ); 
    return $content;
}

This basically just removes the link from around the image.

I’m wondering how to, instead of removing the link entirely, link to the single post page? I think this would be a better solution because I think a lot of people probably click on that first image thinking it will take them to the single post page.

Is there a way to do this by modifying the code above in some way?

Related posts

1 comment

  1. It’s a bit hacky but something like this should work:

    add_filter( 'the_content', 'attachment_image_link_remove_filter' );
    function attachment_image_link_remove_filter( $content ) {
        global $post;
        $post_permalink = post_permalink($post->ID);
        return preg_replace_callback( '#<a(?:.*?(?:wp-att|wp-content/uploads)[^>]*)><img[^>]*></a>#i', function( $match ) use ( $post_permalink ) {
            return preg_replace('#href="[^"]+"#', 'href="' . $post_permalink . '"', $match[0]);
        }, $content ); 
    }
    

    It uses a callback function that then replaces the whole content of the href with post_permalink($post->ID).

Comments are closed.