Detect if is image unattached

I have problem with unattached attachments. I use image.php to show WordPress image gallery. I always show “big image” (for current clicked image)…and under that image I show rest thumbs from that gallery.

I use this code to show “big” image:

$img_attachment = wp_get_attachment_image_src($post->ID, 'medium');
$img_height = $img_attachment[2];
$img_full = wp_get_attachment_image_src($post->ID, 'large');

<div style="text-align:center">
<img src="https://wordpress.stackexchange.com/questions/214471/<?php echo $img_attachment[0]; ?>"/>
</div>

And this code I use to show rest of thumbs from that gallery:

$gallery_shortcode="
';
$gallery_content = do_shortcode($gallery_shortcode);
echo $gallery_content;

And what is problem? Problem is that WordPress use Image.php file for Unattached images too. So if you have 5K of unattached images and someone come from google to one of Unattached images (coz google collect also unattached images no matter if you wont that) then Image.php file will show that image like “big image” and in thumbs under that big image he will show ALL unatached images…so he will list all 5K of images on 1 page!

I think there is 2 solutions.

  1. Somehow detect if image is not attached to any post…and if is that true then not show gallery of thumbs under, or
  2. I need to make some change in second part of code to fix that

How to do one of that?

1 Answer
1

For unattached images, the post_parent column in the wp_posts table, has the value of 0.

Your gallery shortcode in that case is:



which means you are calling get_children() with post_parent as 0.

You can e.g. use the gallery shortcode callback gallery_shortcode() directly:

if( $parent_id = $post->post_parent )
{
    echo gallery_shortcode( 
        [ 
            'id'      => (int) $parent_id, 
            'columns' => 4 
        ] 
    );
}

where we only display the gallery for attached images.

Leave a Comment