0

My gallery has dozens of images. Next to each image, there should be links to the posts attached to that image. (You can see these in Media Library, under "Uploaded To").

I am able to retrieve the post's ID with $attachment_data['uploadedTo'], but how can I get the name of that post?

My loop:

$the_query = new WP_Query( array(
    'post_type' => 'attachment',
    'category_name' => 'photos',
    'posts_per_page' => 25,
));

while ( $the_query->have_posts() ) : $the_query->the_post(); 

$attachment_data = wp_prepare_attachment_for_js($attachment);

      echo '<div><div>
      <img src="'.wp_get_attachment_url ('medium').'"/>
      </div><div><a href="/?p='.$attachment_data['uploadedTo'].'"> Name of Post Goes Here</a></div>';

      endwhile; wp_reset_postdata();?> 
  • 1
    Images can only be attached to a single post at a time. They might be used on multiple pages, but they’re only ever attached to the post that they were first uploaded to (if they were even uploaded to a single post to begin with). – Jacob Peattie May 28 at 9:26
  • You're correct about that. I should mention I am using Advanced Custom Fields to attach more images, but it does limit to one. Good to know! – BlueHelmet May 28 at 10:34
0

I was able to find some helpful articles, the combination of which helped me solve this. First, I discovered that the uploadedTo information can retrieved, returning the ID. A bunch of information on attachment data can be found here.

Second, I was able to convert the ID into a link for the post by simply adding some html <a href="/?p='.$attachment_data['uploadedTo'].'">.

Third, I was able to convert the ID into the name of the post, using the method found here.

All together, I was able to generate a formatted link to the post, from the attachment.

Unfortunately, it won't be a list of posts, since Wordpress only allows posts to have one image attached (even if there technically are more).

The final code:

$the_query = new WP_Query( array(
    'post_type' => 'attachment',
    'category_name' => 'photos',
    'posts_per_page' => 25,
));

while ( $the_query->have_posts() ) : $the_query->the_post(); 

$attachment_data = wp_prepare_attachment_for_js($attachment);
$title = get_post_field( 'post_title', $attachment_data['uploadedTo'] );

      echo '<div><div>
      <img src="'.wp_get_attachment_url ('medium').'"/>
      </div><div><a href="/?p='.$attachment_data['uploadedTo'].'">'.$title.'</a></div>';

      endwhile; wp_reset_postdata();?>

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.