How to get the image attachement custom link with PHP – WordPress

This will return the link to the attachment:

    $link=wp_get_attachment_link($image->ID);

However, I can’t find a way to get the LINK TO value from the ATTACHMENT DISPLAY SETTINGS of an image. See screenshot below.

Read More

enter image description here

Related posts

Leave a Reply

3 comments

  1. As yoavmatchulsky wrote, this field is dynamically filed by ~wp-includes/js/media-views.js after you manually choose an image
    but if you have an id of attachment, use wp_get_attachment_link( $id, $size);
    as size use ‘full’
    full ref. in codex

  2. Or, if you are trying to use a custom link, the method described here might help.

    Basically, in your functions.php, you could add a code similar to this:

    // Adds a custom url field to your attachment
    function attachment_custom_url( $form_fields, $post ) {
            $form_fields['video-url'] = array(
            'label' => 'CustomURL',
            'input' => 'text',
            'value' => get_post_meta( $post->ID, 'custom_url', true ),
            'helps' => 'Add custom URL, if applicable',
        );
        return $form_fields;
    }
    add_filter( 'attachment_fields_to_edit', 'attachment_custom_url', 10, 2 );
    
    function attachment_custom_url_save( $post, $attachment ) {
    if( isset( $attachment['custom-url'] ) )
    update_post_meta( $post['ID'], 'custom_url', esc_url( $attachment['custom-url'] ) );                        
        return $post;
    }
    add_filter( 'attachment_fields_to_save', 'attachment_custom_url_save', 10, 2 );
    

    And then, you could call it in your php like so:

    <?php 
    <a href="'.get_post_meta($post->ID, 'custom_url', true).'">Custom Link</a>;
    ?>
    
  3. I know this is an old thread, but I solve this by getting the post meta of the attachment, which was easier to me.

    In my installation, custom URL input is shown like this:

    <input type="text" class="text" id="attachments-140443-foogallery_custom_url" name="attachments[140443][foogallery_custom_url]" value="https://mycustomurl.com">
    

    So, I assumed that if the first brackets contains the post ID, the second one is a meta key to save this value on wp_postmeta table. And there it was, just starting with the underscore character so it would be a hidden meta data. Therefore, the easier way to get this value is like this:

    get_post_meta( get_post_thumbnail_id( get_the_ID() ), '_foogallery_custom_url', true);
    

    Of course you need to check if the post does have a thumbnail, but that’s easy to adapt.