简体   繁体   中英

How can I make this Php WP_Query returning categories only once?

This loop returns the categories of each post, showing it multiple times. Instead, I want to show categories once, this is a filter by category functionality.

<div id="filter-box" class="filter-box">

        <?php 
            $args = array (
                'post_type'     => "post",
                'post_status'   => "publish",
                'order'     => 'ASC',
                'orderby'   => 'title' ,
                'posts_per_page'    => -1);

        $all_query = new WP_Query($args);

            if ($all_query->have_posts()): 
               while ($all_query->have_posts()): 
                  $all_query->the_post(); 
          ?>
            <a href="#" class="filter-btn" data-cat="<?php get_cat($post->ID); ?>"><?php get_cat($post->ID); ?></a> 
            <?php  
                 endwhile;  
                       endif;
                         wp_reset_postdata();
        ?>

</div>

This is the function from functions.php

 function get_cat($post_id) {
    $category_detail=get_the_category($post_id);
    foreach($category_detail as $cd) {
      echo $cd->cat_name;
    }
  }

Want to display the categories only once as they appear once for each of the posts.

Please modify you code as:

 <?php 
            $args = array (
                'post_type'     => "post",
                'post_status'   => "publish",
                'order'     => 'ASC',
                'orderby'   => 'title' ,
                'posts_per_page'    => -1);

        $all_query = new WP_Query($args);
         $tempArr = array();
            if ($all_query->have_posts()): 
               while ($all_query->have_posts()): 
                  $all_query->the_post();
                  if(!in_array($post->ID , $tempArr)){ // check if array has ID not display
                  array_push($tempArr, $post->ID); //push postID in array
          ?>
            <a href="#" class="filter-btn" data-cat="<?php get_cat($post->ID); ?>"><?php get_cat($post->ID); ?></a> 
            <?php  
                 }
                 endwhile;  
                       endif;
                         wp_reset_postdata();
        ?>

Explanation: Please declare an array as $tempArr = array(); and then check if $temArr array has that postID if not then display category and push it in array.

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