最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

remove links from images using functions.php

matteradmin9PV0评论

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

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

Share Improve this question edited Nov 14, 2011 at 19:24 digitalbart asked Nov 14, 2011 at 19:10 digitalbartdigitalbart 2171 gold badge2 silver badges7 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 5
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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far