我正在为我的网站制作一个Wordpress主题,我想根据类别显示当前文章的所有相关帖子 .
所以,例如,如果我有这个结构:
-
父类别1
-
儿童类别1
-
儿童类别2
-
儿童类别3
-
大孩子类别1
-
父类别2
-
儿童类别4
-
儿童类别5
-
大童2类
如果帖子在 Parent Category 中,我想要检索该类别的帖子以及来自其子级和格兰儿童类别的帖子 .
如果帖子在 Child 或 Gran Child Category 中,我想检索父类别,然后获取上述所有帖子 .
我得到了这个按预期工作的脚本,但我不确定它是最好的解决方案(我在Wordpress'开发者资源中找不到任何有用的信息) .
$parent = array();
$children = array();
$category = get_the_category($post->ID);
if($category):
foreach ($category as $cat):
if($cat->parent != 0) :
$ancestors = get_ancestors($cat->term_id,'category');
$parent[] = end($ancestors);
else:
$parent[] = $cat->term_id;
endif;
endforeach;
endif;
if($parent):
foreach ($parent as $par):
$child_categories = get_categories(
array( 'child_of' => $par )
);
foreach($child_categories as $chi):
$children[] = $chi->slug;
endforeach;
endforeach;
endif;