I made custom post type "Collections" and I populate every post through featured image. Now I need to link every featured image to appropriate external link. So far I managed to add meta box to media uploader with this piece of code in functions.php:

    function be_attachment_field_credit( $form_fields, $post ) {

    $form_fields['be-url'] = array(
        'label' => 'URL',
        'input' => 'text',
        'value' => get_post_meta( $post->ID, 'be_url', true ),
        'helps' => 'Add URL',

    return $form_fields;

add_filter( 'attachment_fields_to_edit', 'be_attachment_field_credit', 10, 2 );

function be_attachment_field_credit_save( $post, $attachment ) {

    if( isset( $attachment['be-url'] ) )
update_post_meta( $post['ID'], 'be_url', esc_url( $attachment['be-url'] ) );

    return $post;

add_filter( 'attachment_fields_to_save', 'be_attachment_field_credit_save', 10, 2 );

And then in my single.php I add

echo get_post_meta(get_post_thumbnail_id(), 'be_url', true);

Now, when I click on featured image in admin panel in order to populate the meta box with url (for example http://www.google.com), the metabox saves the link, but when I go to my page where my featured image is, the featured image is not linked at all. How do i make my featured image go to external link? Thanx.

  • Could you add the code in your template that is supposed to show the link? – cjbj Sep 10 '16 at 9:15
  • Sure, sorry, I just did. Any suggestions? – Nancy Sep 10 '16 at 9:36
  • It looks like you are storing the url as a meta value of the post, while you are trying to retrieve it as a meta value of the post attachment. – cjbj Sep 10 '16 at 9:45
  • Sorry to be very persistant, but I am a newbie and do not know how to resolve this myself. Can you show me the right code that will do what I want? I m lost. – Nancy Sep 10 '16 at 9:51

In WordPress attachments are treated as posts, with their own titles, excerpts and metavalues. So if a post has an attachment there are two sets of metavalues, one for the post itself and one for the attachment.

You are using update_post_meta( $post['ID'] ... to store the url. So it is stored as a metavalue of the post.

You are retrieving with get_post_meta(get_post_thumbnail_id() ..., so you are looking for a metavalue of the attachment. To retrieve it you must not use get_post_thumbnail_id() but $post['ID'], because that's where you stored that url.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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