开发者

Hide Div if no image in the loop

Im looking to create a condition 开发者_运维技巧in wordpress loop. if no image then image box (.thumbHome{display:none})

this is in my function.php

function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' .   $iPostID );
if($arrImages) {
    $arrKeys = array_keys($arrImages);
    $iNum = $arrKeys[0];
    $sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
    $sImgString =  '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}  

And my javascript:

window.onload = noImage();
 function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}

I tried:

window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
} 

RESULT: class hide added to all loop

I cant figure it another way, since im still new in coding.

thx


Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.

Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.

In your main loop, add an unique id to each .thumbHome div based on the image id. So like:

echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent

Then your else conditional (for whether there's a thumbnail) could be changed to:

else {
    echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}

and your js function could be:

function noImage(var){
    $(var).hide();
}

This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜