【问题标题】:Get all category with post - Wordpress使用帖子获取所有类别 - Wordpress
【发布时间】:2019-02-12 19:06:03
【问题描述】:

我需要获取所有类别和类别 ID。并使用此代码显示:

echo '<li><a data-filter=".portfolio-'.$category->cat_ID.'" href="'.$cat_link.'">'
  . $category->name.'</a></li>';

我有 3 个不同类别的帖子,但我的循环给了我 6 个类别名称(2 个重复)。

<?php
$query = array(
    'post_type'      => 'post',
    'parent'         => '',
    'orderby'        => 'id',
    'order'          => 'DESC',
    'hide_empty'     => 1,
    'hierarchical'   => 1,
    'taxonomy'       => 'category'
);

$category_home = new WP_Query( $query );
if ( $category_home->have_posts() ) {
    while ( $category_home->have_posts() ) {
        $category_home->the_post();
        $categories = get_categories($args);
        foreach($categories as $category):
            $cat_link = get_category_link($category->cat_ID);
            $cat_name= $category->name; 
            echo '<li><a data-filter=".portfolio-'.$category->cat_ID.'" href="'.$cat_link.'">'.$category->name.'</a></li>';
        endforeach; 
    }
}

【问题讨论】:

  • 我猜你在 while 循环之后错过了wp_reset_postdata();
  • @DmitryS。我尝试 wp_reset_postdata();在循环中的不同位置。此代码没有帮助。
  • 当我使用:$categories = get_the_category($args); 不是 $categories = get_categories($args); 然后我有 3 个类别,等等 CAT 1、CAT 2、CAT 3,但是当我在一个类别中有 2 个条目时,我有 CAT 1 ,CAT 1,CAT 2。但我只想拥有一次 CAT 1。有什么解决方案吗?

标签: php wordpress loops


【解决方案1】:
$args = array(
   'orderby' => 'id',
   'hide_empty'=> 0,
   'exclude'   => 1, //Child From Boxes Category 
);
$categories = get_categories($args);
foreach ($categories as $cat) {
   $category_link = get_category_link( $cat->cat_ID );
   echo '<li><a data-filter=".portfolio-'.$cat->cat_ID.'" href="'.$category_link.'">'.$cat->name.'</a></li>';
}

【讨论】:

  • 太棒了,这就是我想要的!我只是改变'orderby' =&gt; 'id', 'hide_empty'=&gt; 1,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-23
相关资源
最近更新 更多