Tuesday, 16 March 2010

Suppressing Link URL In WP Media Library

UPDATE: You can now set the default action by adding the following code to your functions.php file.


It's been a while since I've posted anything here (I've been pretty busy lately), so when I threw together a quick fix for a WordPress installation today, I thought I should put a quick note about it here.

The Problem:
When inserting or attaching an image to a post with WP's Media Library the Link URL is always pre-populated with the URL to the file. To remove this URL so that the image is not linking to the original file, users must go through the arduous process of remembering to click the "None" button before inserting the image.

OK, that was a little sarcastic, but that's pretty much what the feature request was saying. They wanted the field's behaviour to change so that the default was blank.

The Solution:
To create the desired behaviour, I created the following function and hooked it to the attachment_fields_to_edit filter to clear out the URL before it is displayed.

// hide the URL by default for people too lazy to click "None"
add_filter('attachment_fields_to_edit', 'suppress_linkURL');
function suppress_linkURL($fields) {
$img_url = $fields['image_url']['value'];
$html = $fields['url']['html'];
if(!empty($html)) {
$fields['url']['html'] = str_replace("value='$img_url'","value=''",$html);
return $fields;

I doubt there is going to be a lot of demand for this particular snippet of code, but hopefully somebody will find it helpful.

1 comment:

  1. That was unnecessarily sarcastic! :-)

    The default WP insertion of a link to the image is a bizarre behavior. Why on earth would one want blog readers to see a link if they hover over an image and then just see the image if they click on it? And it looks to me like spiders see these links as 404 errors, which could be bad SEO.

    OK, if you have your head together when you add an image it is easy to click the 'none' button, but if, say, your average office junior has the task of updating the website it's not going to be in the forefront of their mind.

    It would be much better for it to default to none and then have the option of adding the link as a positive choice.