Ahh, the self linking image, the bane of so many WordPress users. So, you have a site with a ton of content where unscrupulous publishers, admins, and contributors left the Attachment Display Settings “Link To” option to its dreaded default. Sure, you can prevent that moving forward and stop automatically hyperlinking images, but what about your existing content that’s riddled with self linking images (dare I call them “WP Selfies”)? I threw together a quick function—a dangerous function if used incorrectly—to remove self linking images from your existing content once and for all.
**MAKE A DATABASE BACKUP**
In case you missed that ^ please backup your database before using this snippet. That backup is the only way to undo this action. The action is even commented out in the snippet because you should only run this once and very deliberately (you’ll need to uncomment it when you’re ready). It could take a while depending on the amount of content you have. The site I used it on had ~500 posts and it took around 30 seconds.
This snippet parses each post’s or page’s content one by one. It looks for any
img inside an anchor tag and if the image URL is the same as the anchor’s
href URL then it replaces the entire anchor with just the
img tag that was within it.
It’s not perfect but it got the job done for me. If you want to suggest improvements then please leave a comment.