Changing First Image Link to Single Post

In category archives i use the_content to pull image with a text. I want this image to link to a post. I have problems making it work because my first images in posts either are linking already to external site or they aren’t.

I know of two ways to do it.
1. I delete first image from the_content and then use the_post_thumbnail().

function remove_first_image ($content) {
$content = preg_replace("/<img[^>]>/i", "", $content, 1);
} return $content;
add_filter('the_content', 'remove_first_image');

It works. But it only strips image. I have a lot of posts that are also links. How to change this code so it removes first image with a link if it already exist? I tried adding this.

$content = preg_replace("/<a href[^>]>/i", "", $content, 1);

But it’s not good enough. It does strip link. But if image does not have a link it strips next link. Which is often the_content more-link. I tried mixing a href and img within one preg_replace but can’t make it work.

  1. Second option would be simply changing/adding a href to image. For which i found this code.

    $content = preg_replace("/<img[^>]+>/i","", $content, 1);<br>
    $old = '/(<img[^>]+/>)/i';<br>
    $new = '<a href="'.esc_url(get_permalink()).'" title="'.esc_attr(get_the_title()).'">$1</a>';<br>
    $content = preg_replace($old, $new, $content, 1);

This one is good enough as well. But has the same issue as previous method. Because my images are both with a href and without.

I think what i am looking for is preg_replace code for in one line, unless there is more simpler way to it

Can you help me out with this? Also which method would be better to use. That is more lighweight.

Read more here: Changing First Image Link to Single Post

Leave a Reply

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