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.

Just as the title says i want to replace the term from a custom taxonomy with an image, but only in one custom loop and not in the main loop.

So i have a custom taxonomy named Tax1 that has two terms: Term1 and Term2. I use the following code to list the terms (i.e. Term1 or Term2) in the main loop:

echo get_the_term_list( $post->ID, 'Tax1', ' ', ', ', '' );

But for my custom loop i would like to have an image instead of the text term. I think this should be possible but i'm no good with php.

So how can i achieve this?

Thanks!!!

share|improve this question

1 Answer 1

up vote 1 down vote accepted

This is a quick and easy solution if you only have two terms and don't need a way to change those pictures in the backend.

It assumes that inside your theme you have a folder "term_imgs" with *.png files names according to the slugs of your terms.

$terms = get_the_terms( $post->ID, 'Tax1' );
$out = array();
if ( $terms && ! is_wp_error( $terms ) ) {
    if ( !empty( $terms ) ) {
      foreach ( $terms as $term ) {
        $out[] = '<a href="'.get_term_link( $term->slug, 'Tax1' ) .'"><img alt="'.$term->name.'" src="'.get_template_directory_uri().'/term_imgs/'.$term->slug.'.png"></a>';
      }
      echo implode(',', $out );
    }
}

You can call this folder however you want, just change the according piece of code, e.g.

$out[] = '<a href="'.get_term_link( $term->slug, 'Tax1' ) .'"><img alt="'.$term->name.'" src="'.get_template_directory_uri().'/other_folder/'.$term->slug.'.jpg"></a>';
share|improve this answer
    
it works, but only for the first post in the loop. The second post has 2 images (for both terms), the third has 3 images and so on... –  CK13 Feb 17 at 14:04
    
I just updated my answer. $out needs to be reset. –  kraftner Feb 17 at 14:10
    
Thank you very much. I got it working. –  CK13 Feb 17 at 14:46

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.