开始很容易。让我们获取2015年的所有帖子:
$posts = new WP_Query( \'year=2015\' );
现在,我们有一个post对象数组,我们必须将其分类,如果它们有多个类别,则复制它们。结果进入多维数组。
$categorized_posts = array ();
foreach ($posts as $post) {
$post_cats = wp_get_post_categories ($post->ID, array(\'fields\' => names));
foreach ($post_cats as $post_cat) {
$categorized_posts[$postcat][] = $post->ID;
}
}
所以
$categorized_posts
是一个具有类别名称的数组,对于每个类别名称,都有一个对应帖子的ID数组。缺少的是层次结构树。我们将循环浏览所有类别,并将它们与相应的帖子标题一起打印。为了按层次进行此操作,我们使用
the recursive function found here, 我们对其进行修改以输出帖子标题。
// this goes in the template where you want the tree to be printed
wpse237979_hierarchical_category_tree (0, $categorized_posts );
// this goes in functions.php
function wpse237979_hierarchical_category_tree ( $cat, $categorized_posts ) {
$next = get_categories(\'hide_empty=false&orderby=name&order=ASC&parent=\' . $cat);
if ($next) {
foreach ($next as $cat) {
if (array_key_exists($cat,$categorized_posts)) {
echo \'<ul><li><strong>\' . $cat->name . \'</strong>\';
// now loop through the gathered ID\'s of posts belonging to this category
$current_cat_posts = $categorized_posts[$cat];
foreach ($current_cat_posts as $current_cat_post) {
$this_post = get_post ($current_cat_post);
echo \'<h2>\' . $this_post->post_title . \'<h2>\';
}
}
wpse237979_hierarchical_category_tree( $cat->term_id, $categorized_posts );
}
}
echo \'</li></ul>\'; echo "\\n";
}
注意:我并没有实际测试这段代码,所以可能需要进行一些调试,但我相信您已经了解了总体思路。