0

I've set up a custom loop to output posts from a custom post type resource section I've created. Each separate resource has been categorized within two different taxonomies, one for the clinical area that the resource is talking about, as well as one for the type of resource it is. The clinical area terms are being output as a list of terms, which is all good to go. However, I want the resource type to display as icons (from Font Awesome). I've gotten it to work if only one resource type term is checked with:

    <?php if(has_term('webinar', 'type')) : ?>
      <i class="fa fa-desktop" aria-hidden="true"></i>
    <?php elseif(has_term('report', 'type')) : ?>
      <i class="fa fa-file-text-o" aria-hidden="true"></i>
    <?php elseif(has_term('video', 'type')) : ?>
      <i class="fa fa-youtube-play" aria-hidden="true"></i>
    <?php elseif(has_term('past-project', 'type')) : ?>
      <i class="fa fa-cogs" aria-hidden="true"></i>
    <?php elseif(has_term('meeting-material', 'type')) : ?>
      <i class="fa fa-users" aria-hidden="true"></i>
    <?php elseif(has_term('info-sheet', 'type')) : ?>
      <i class="fa fa-info-circle" aria-hidden="true"></i>
    <?php else : ?>
      <i class="fa fa-link" aria-hidden="true"></i>
    <?php endif; ?>

But obviously, as I've just dim-wittedly realized, this doesn't work if multiple terms are selected. It just retrieves the first term and outputs that one icon. Instead I want it to output multiple icons if multiple terms are checked.

So my question is if there's any way for me to set this up as an IF/AND scenario, without having to build a bunch of custom has_term(array('webinar', 'report'), 'type') -type statements?

1 Answer 1

3

Firstly, create some sort of association between the icon class and the term name:

$icons = array(
    'webinar'          => 'fa-desktop',
    'report'           => 'fa-file-text-o',
    'video'            => 'fa-youtube-play',
    'past-project'     => 'fa-cogs',
    'meeting-material' => 'fa-users',
    'info-sheet'       => 'fa-info-circle',
);

Then loop through each term assigned to the post and output the corresponding icon:

$terms = get_the_terms( get_the_ID(), 'type' );

if ( $terms && ! is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {
        $class = isset( $icons[$term->slug] ) ? $icons[$term->slug] : 'fa-link';

        echo '<i class="fa ' . $class . '" aria-hidden="true"></i>';
    }
}
1
  • 1
    Jacob, you are a dang genius. Thank you ever so much for this clear and concise answer!
    – Connie
    Mar 6, 2018 at 6:24

Your Answer

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

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