0

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!!!

1 Answer 1

1

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>';
2
  • 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, 2014 at 14:04
  • I just updated my answer. $out needs to be reset.
    – kraftner
    Feb 17, 2014 at 14:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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