Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Add conditional to wp_get_attachment WordPress

  • SOLVED

Hello! I have the code below that pulls in all the images from a post and throws them into a gallery with thumbnails and a large image (see attached).

So what I'd like to do is, if there is only one image attached to the post, I want to remove the single thumbnail. Since the gallery and thumb are dynamically generated, I'm not really sure what kind of conditional statement I'm looking for. I could just hide it with .css. So, if there is only one image, trigger a .hide class or something.

Any help is appreciated.


<?php
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);
$attachments = get_posts($args);
if ($attachments) {
foreach ($attachments as $attachment) {
echo "<li>";
echo wp_get_attachment_link($attachment->ID, 'featured-portfolio', false, false);
echo "</li>";
}
}
?>





Answers (2)

2011-05-30

Aneesh Joseph answers:

Change
if ($attachments)
to
if(count($attachments)>1)



get_posts($args) returns an array and we can check its length using count($array)

Reference :
1. [[LINK href="http://php.net/manual/en/function.count.php"]]http://php.net/manual/en/function.count.php[[/LINK]]
2. [[LINK href="http://codex.wordpress.org/Template_Tags/get_posts"]]http://codex.wordpress.org/Template_Tags/get_posts[[/LINK]]

2011-05-30

Denzel Chia answers:

Hi Mike,

What Aneesh says is correct.
But perhaps you need it added to your code.
So here it is.


<?php

$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);

$attachments = get_posts($args);
$counter = 0;
$counter = count($attachments); // count number of attachments.

if ($attachments) {

foreach ($attachments as $attachment) {

echo "<li>";

echo wp_get_attachment_link($attachment->ID, 'featured-portfolio', false, false);

echo "</li>";
}
}
?>


<?php

if($counter==1){
//echo your css code here to hide your thumbnail if there is only one image attachment.
//this if condition can be put anywhere on you template, after you thumbnail code,
//so that your echo css can hide the generated thumbnail

}

?>



Thanks.
Denzel


Mike McAlister comments:

Thanks Denzel, this is what I was looking for! Aneesh was close, but this one got it done.