remove links from images using functions.php

by digitalbart   Last Updated February 19, 2019 01:08 AM

I am looking for a way to remove the attachment link from images in the post content.

I would like to add this to the functions.php in my theme. I know you can disable this in the post on a per image basis, but I would like to do this just once in my functions.php page. Any ideas?

Thanks, Bart



Answers 2


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;
}

The regex could be simpler and unfortunately this also deprives you of the unique wp-image-xxx (where xxx is the attachment ID) class of the <img> tag, but it's the safest one I could come up with to only remove links around attachment images and leave in-text links as well as links around non-attachment images intact.

If you don't care about non-attachment images and want all images within the post content to not be wrapped in links anyway, this should suffice:

function attachment_image_link_remove_filter( $content ) {
    $content =
        preg_replace(array('{<a[^>]*><img}','{/></a>}'), array('<img','/>'), $content);
    return $content;
}

I can see it breaking things though, if the inside of an anchor ends in some other self-closing element, such as a <br /> tag. That would be rare, obviously, but I'd recommend using the first, though longer version.

Johannes Pille
Johannes Pille
November 15, 2011 06:04 AM

Can i use this code to remove all image attachment page links ? (intrested ONLY removing attachment page links) i have a blog were i have 17.000 posts and most of them have at least one image that is linked to post and since that yoast mistake i have this problem.

Thanks

cezars
cezars
February 19, 2019 00:55 AM

Related Questions


Custom html for images

Updated April 12, 2017 06:08 AM


How to make this code work

Updated November 26, 2018 12:08 PM