4

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="<?php echo $img_attachment[0]; ?>"/>
</div>

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

$gallery_shortcode = '[gallery id="' . intval( $post->post_parent ) . '" columns="4"]';
$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?

3

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

Your gallery shortcode in that case is:

[gallery id="0" columns="4"]

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.

2
  • TNX..this is perfect...you saved me lot of bandwidth :) I just read now this coz I was too busy to implement. This works perfect. Tnx again! Feb 18 '16 at 18:18
  • great, glad to hear it worked for you ;-) @NebojsaLukic
    – birgire
    Feb 18 '16 at 18:54

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.