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.