简体   繁体   中英

Looping through categories in WordPress

I have a number of products, which will be displayed in different categories when ticked.

Now, what I am trying to achieve, is certain images to be shown depending on which categories are clicked.

Example.

IF I clicked category A, then an image (A) would be shown.

I am doing this as the code shows below.

<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>

    <?php 
    $terms = wp_get_post_terms( get_the_id(), 'type' );
    $term_class = '';
    if ( isset( $terms[0] ) ) {

        $term_class = $terms[0]->slug;
    }
    ?>
<ul>
            <li class="linoheight" style="margin-left:45px !important;"><img class="<?php echo $term_class; ?>-new" src="<?php bloginfo('stylesheet_directory'); ?>/images/acoustic-icon-small.png" alt="" width="30px" height="30px" style="display:none;"></li>
            <li class="linoheight"><img class="<?php echo $term_class; ?>-new" src="<?php bloginfo('stylesheet_directory'); ?>/images/hard-wired-icon-small.png" alt="" width="30px" height="30px" style="display:none;"></li>
            <li class="linoheight"><img class="<?php echo $term_class; ?>-new" src="<?php bloginfo('stylesheet_directory'); ?>/images/radio-icon-small.png" alt="" width="30px" height="30px" style="display:none;"></li>
        </ul>

So, this will get the checkbox which is selected, and then create the class 'categoryA-new.

In the CSS, this category will be display:block, which displays the icon.

Now, the issue I am having, is that <?php echo $term_class;?>-new is only getting one of the categories, which means if category A is selected, then category B and C are still showing images.

I have a feeling this is an issue with the loop, does anyone have any ideas?

You just need to hide and show the object if onclick then a unique id of that item should be passed to some jquery or javascript function and they will show the item eg, if I have

  • item 1
  • item 2
  • item 3

these three fields have unique id,s in them like for 1- 2- etc you need to use jquery hit like this after placing some unique id at the ul like first to catch the in between li,s :

$("#list-of-items li").click(function(){

    var current_clicked_li_index = $(#list-of-items li).index(this);

   // now use .each loop in jquery

$("#list-of-items li img").each(function( Loopindex ) {


   if(current_clicked_li_index != Loopindex){

      $(this).hide();

   }else{

    $(this).show();

   }

});   

});

Note: don't forget to use the jquery library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM