WordPress attachments hack
While working on a WordPress site recently I came up against a problem that had never occurred to me before. The client wanted each post excerpt on the homepage to include an image which when clicked would link to the main post (permalink) itself. The built in functions of wordpress when inserting an image allow you to link to either the 'File URL' (i.e. the full size version of the image) or to the 'Post URL' which is actually an attachment page in wordpress which displays the image, but does not include the text of the actual post itself. However, without either editing the html of each post (not an option for this client) or inserting the image without a link, and then adding the permalink to the image (too long winded) there was no simple way to create the image links in the way they wanted them.
My solution to this was to create a very basic hack which would allow them to use the 'Post URL' link when inserting images, but instead of linking to the attachment page, the link would automatically be updated to link to the post's permalink itself.
Here is the basic php function that you would need to insert into your theme's functions.php file:
function lose_attachment($content){
return preg_replace('/<a(.*?)href="(.*?)\/attachment\/(.*?)"/i', '<a$1href="$2"', $content);
}
add_filter('the_excerpt', 'lose_attachment',2);
This will remove the 'attachment/name-of-image-file' part from the URL making it link to the post's permalink itself. I hope someone out there finds this useful!















really good post….tutorial is very helpful for me …thanks a lot for giving out such good tutorials
This was a great help. Thanks for sharing the code
This is a great little hack
Simple but effective!
I can’t wait to try this out.
Thanks for the code dude, i need to try this out on my wordpress blog! As im learning advanced use of it.