EDIT:
好吧,下面的方法似乎有点消耗DB。彼得古森
posted a very interesting alternative. 由于这种方法已经被接受为我不知道的正确答案,所以有可能将这个问题标记为重复。我标记了我的答案,以便主持人可以看一下。谢谢
我首先收集多维数组中的所有数据。子阵列是类别。
因此,我首先加载所有类别get_categories()
. 它们是按标题排序的。我把它们都装进$post_categories
而数组键是类别的ID。名称等类别信息将存储在$post_categories[ category_id ][\'cat\']
.
在此之后,我运行查询,但我确保它是按标题排序的。现在,我得到了帖子所附的所有类别,并将帖子保存在其中$post_categories[ category_id ][\'posts\']
.
现在我有了一个多维数组,我只输出了两个foreach()
循环。
$args = array(
\'type\' => \'projetos\'
);
$all_categories = get_categories( $args );
$post_categories = array();
foreach( $all_categories as $category )
$post_categories[ $category->term_id ][\'cat\'] = $category;
$args = array(
\'post_type\' => \'projetos\',
\'orderby\' => \'title\',
\'order\' => \'asc\'
);
$my_query = new WP_Query( $args );
if( $my_query->have_posts() ) {
while ($my_query->have_posts()){
$my_query->the_post();
$p = array();
$p[\'permalink\'] = get_the_permalink();
$p[\'title\'] = get_the_title();
foreach( get_the_category() as $category )
$post_categories[ $category->term_id ][\'posts\'][] = $p;
}
}
foreach( $post_categories as $cat ){
if( ! isset( $cat[\'posts\'] ) || count( $cat[\'posts\'] ) == 0 )
continue;
?>
<strong><?php echo $cat[\'cat\']->name; ?></strong><br />
<?php
foreach( $cat[\'posts\'] as $post ):
?>
<a href="<?php echo $post[\'permalink\']; ?>"><?php echo $post[\'title\']; ?></a><br />
<?php endforeach;
}
wp_reset_query();