Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm using the Taxonomy Images plugin to output thumbnails next to my tax terms.

I'm using get_term_children in a foreach loop to pull out the terms, and a sub-foreach loop to pull out the thumbnail images.

Things are working fine, except the images get printed twice. I must be doing something wrong with one/both of the loops.

Anyone see any obvious foreach issues?

<?php
$termID = 10;
$taxonomyName = "tool";
$termchildren = get_term_children( $termID, $taxonomyName );
$termThumbs = apply_filters( 'taxonomy-images-get-terms', '', array('taxonomy'=> 'tool'));

echo '<ul>';
foreach ($termchildren as $child) {
    $term = get_term_by( 'id', $child, $taxonomyName );
    echo '<li>';
    echo wp_get_attachment_image( $termThumb->image_id, 'thumb' )   ;

        if ( ! empty( $termThumbs ) ) {
        foreach(  $termThumbs as $termThumb ) {
            print wp_get_attachment_image( $termThumb->image_id, 'thumb' )  ;
        }
    }

    echo '<a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a>';
    echo '</li>';

}
echo '</ul>';
?> 

The screenshot: http://cl.ly/1y2q2J0S0m3x0e0T0N1D

share|improve this question
    
You're echoing the image first and then printing it in another loop. Why? –  Johannes Pille May 3 '12 at 13:41
add comment

1 Answer

1). Inside your foreach (term child) loop you first have:

echo wp_get_attachment_image( $termThumb->image_id, 'thumb' )   ;

but $termThumb isn't set yet. So on the first iteration it doesn't do anything.

2) Then you have another foreach loop:

if ( ! empty( $termThumbs ) ) {
    foreach(  $termThumbs as $termThumb ) {
        print wp_get_attachment_image( $termThumb->image_id, 'thumb' )  ;
    }
}

where $termThumbs is (presumably) an array of term-thumbnail objects. So you print every term thumbnail image.

Then on the next iteration of the foreach (i.e. the for the next term child) $termThumb is now set to the last object in the $termThumbs array. And so in (1) the term is now set, and so prints the thumbnail for that object, before doing (2) again displaying all thumbnails again.

share|improve this answer
    
So, I need to set $termThumb outside the foreach, and then just echo it inside? This doesn't work: gist.github.com/2585777 but should be close? –  saltcod May 3 '12 at 13:50
    
Get rid of the inner foreach and find a way of get $termThumb->image_id from the current $term object. But I wouldn't know how you'd do that because I'm not familiar with Michael's plug-in - it's probably in the plug-ins documentation. –  Stephen Harris May 3 '12 at 13:54
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.