Find the post an attachment is attached to

So, if you start with this:

$all_images = get_posts( array(
'post_type' => 'attachment',
'numberposts' => -1,
) );

Then $all_images is an array of objects. Step through each one:

foreach ( $all_images as $image ) {}

Inside that foreach, you can use the normal parameters available to the $post object:

  • $image->ID is the ID of the attachment post
  • $image->post_parent is the ID of the attachment post’s parent post

So, let’s use that, to get what you’re after, using get_the_title() and get_permalink():

// Get the parent post ID
$parent_id = $image->post_parent;
// Get the parent post Title
$parent_title = get_the_title( $parent_id );
// Get the parent post permalink
$parent_permalink = get_permalink( $parent_id );

That’s pretty much it!

Putting it all together:

<?php
// Get all image attachments
$all_images = get_posts( array(
'post_type' => 'attachment',
'numberposts' => -1,
) );
// Step through all image attachments
foreach ( $all_images as $image ) {
    // Get the parent post ID
    $parent_id = $image->post_parent;
    // Get the parent post Title
    $parent_title = get_the_title( $parent_id );
    // Get the parent post permalink
    $parent_permalink = get_permalink( $parent_id );
}
?>

Leave a Comment