Get title of post image is attached to

This kind of works but it is outputting 1 post title in particular and for all the images on the page. Any thoughts as to why its not dynamically picking up each images associated post title?

$attachments = get_posts( $args );
foreach ( $attachments 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 );
}

This code loops over each image. Let’s debug it by hand.

As an example, let’s assume there are 3 images.

The first image has a parent ID of 1, a title of “Foo” and link to that post,
The second image has a parent ID of 2, a title of “Bar” and link to that post,
The third image has a parent ID of 3, a title of “Baz” and link to that post,

So, the first time through the loop:

$parent_id is set to 1,
$parent_title is set to Foo,
$parent_permalink is set to the link to Foo.

The second time through the loop:

$parent_id is set to 2,
$parent_title is set to Bar,
$parent_permalink is set to the link to Bar.

All the data for the post “Foo” is overwritten with the data for post “Bar”. Why? Because the code does not save that other data before writing the new data to $parent_id, $parent_title and $parent_permalink.

On the third trip through the loop:

$parent_id is set to 3,
$parent_title is set to Baz,
$parent_permalink is set to the link to Baz.

All the data for the post “Bar” is overwritten with the data for post “Baz”.

When this loop is done, the $parent_id, $parent_title and $parent_permalink variables only hold whatever data is in the last item of the $attachments array. So, the reason that only the last parent post is being used is because that is what the code told PHP to do. The code says, “Throw away those other values.”

What you probably want to do is something like this:

$images = get_posts( $args );

if ( $images ) {

    foreach ( $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 );

        $logoimg = wp_get_attachment_image( $image->ID, 'Work Gallery' );