I'm looking for a code to put in my custom-functions.php that will only disable the links to images that link to an image (jpg, jpeg, png, gif, ect.)

I used this code provided from this page: remove links from images using functions.php

This is the code I inserted in my custom-functions.php

add_filter( 'the_content', 'attachment_image_link_remove_filter' );

function attachment_image_link_remove_filter( $content ) {
$content =
            '{ wp-image-[0-9]*" /></a>}'),
        array('<img','" />'),
return $content;

but it is too robust and disabled every link that is wrapped around an image. I still want links to work that point to pages, posts, pdfs, docs.

Could any of you help? Maybe modify the code above to recognize image extensions and only disable those?

Thank you kindly.

1 Answer 1


I am not a professional when it comes to regular expressions but this should be able to catch all linked images which the href attribute links to an image file ((png|jpg|gif|jpeg|bmp) feel free to add/remove extensions):

add_filter('the_content', function($c){
    return preg_replace_callback("#<\s*?a\b[^>]*>(.*?)</a\b[^>]*>#s", function($m){
        $tpl = $m[0];
        $cnt = isset($m[1]) ? $m[1] : null;

        if ( preg_match('/<a(.*?)?href=[\'"]?.+\.(png|jpg|gif|jpeg|bmp)[\'"]?(.*?)?><\/a>/i', str_replace($cnt, '', $tpl)) ) {
            return $cnt;
        } else {
            return $tpl;
    }, $c);

I tested it locally and it is working, let me know if that helps.

  • It didn't work for my website. I have an image links to a pdf and it still disabled it. Also, something in the code made the homepage not load the rest of the page after the banner slider.
    – Tom T.
    Feb 9, 2017 at 22:45
  • Okay Tom, I see. Can you provide me with a paste of your HTML? use pastebin.com to create a secret and expiring paste of code..
    – Ismail
    Feb 9, 2017 at 22:49
  • I made an improvement to the patterns @TomT. see http://pastebin.com/GE31rzrw
    – Ismail
    Feb 9, 2017 at 23:30
  • I think your new code edit worked!!!! Thank you so much!
    – Tom T.
    Feb 10, 2017 at 21:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.