WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I wanted to link images in a gallery to a custom URL.

I know I could add an extra field and do it this way

I found this ticket on Trac, though, that modifies the "Link URL" field to accept custom links. I like how that works and I'd like to make that work.

Trouble is, I can't seem to figure out how to access the data. I'm using get_children to create an array to loop through. The Link URL is not included in the results.

I've tried get_attachment_link - the trouble is, it doesn't just pull it from the field, the function generates the link itself.

Any ideas? Thanks!

share|improve this question
up vote 4 down vote accepted

On the Trac ticket you've linked at the bottom there is a solution to make it work

function _save_attachment_url($post, $attachment) {
    if ( isset($attachment['url']) ) 
        update_post_meta( $post['ID'], '_wp_attachment_url', esc_url_raw($attachment['url']) ); 
    return $post;
add_filter('attachment_fields_to_save', '_save_attachment_url', 10, 2);

function _replace_attachment_url($form_fields, $post) {
    if ( isset($form_fields['url']['html']) ) {
        $url = get_post_meta( $post->ID, '_wp_attachment_url', true );
        if ( ! empty($url) )
            $form_fields['url']['html'] = preg_replace( "/value='.*?'/", "value='$url'", $form_fields['url']['html'] );
    return $form_fields;
add_filter('attachment_fields_to_edit', '_replace_attachment_url', 10, 2);

So after this code you will be able to add your custom links in the "Link URL" field.

And to get it you just need the attachment ID and you can get it with:

get_post_meta( $post->ID, '_wp_attachment_url', true );
share|improve this answer
Ahhh.. Thank you! :) Works perfectly. – Jonathan Wold Apr 14 '11 at 19:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.