dongyi1982 2019-01-28 15:00 采纳率: 0%
浏览 86

如何让这个Php WP_Query只返回一次类别?

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.

  • 写回答

1条回答 默认 最新

  • du3932066 2019-01-28 15:13
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示