Brian Brian -4 years ago 106
MySQL Question

WordPress Custom Category Show image

I Have a Problem, I am trying to show a country Flag on different custom posts in a category, the code i am using works but when there is more than 1 category assigend to a custom post, the images do not show.

Here is my code:



<?php
$terms = get_the_terms(get_the_ID(), 'story_category' );
if ( $terms[0]->slug == "usa-freebies" ) :?>
<img class="country" width="23" src="http://www.iconarchive.com/download/i47330/icons-land/vista-flags/United-States-Flag-1.ico">
<?php elseif ( $terms[0]->slug == "uk-freebies" ) : ?>
<img class="country" width="23" src="http://www.iconarchive.com/download/i47324/icons-land/vista-flags/United-Kingdom-Flag-1.ico">
<?php elseif ( $terms[0]->term_taxonomy_id == "698" ) :?>
<img class="country" width="21" src="https://cdn2.iconfinder.com/data/icons/Siena/256/globe%20blue.png">
<?php endif; ?>




Answer Source

Right now, you are showing the $terms[0] . 0 is the first position of $terms array so it will always show the first category. You will have to modify your code and run a foreach loop :

<?php

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

    foreach($terms as $current_term){
        if (  $current_term->slug == "usa-freebies" ) :?>
         <img class="country" width="23" src="http://www.iconarchive.com/download/i47330/icons-land/vista-flags/United-States-Flag-1.ico">
        <?php elseif ( $current_term->slug == "uk-freebies" ) : ?>
         <img class="country" width="23" src="http://www.iconarchive.com/download/i47324/icons-land/vista-flags/United-Kingdom-Flag-1.ico">
         <?php elseif ( $current_term->term_taxonomy_id == "698" ) :?>
         <img class="country" width="21" src="https://cdn2.iconfinder.com/data/icons/Siena/256/globe%20blue.png">
        <?php endif; 
    }
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download