WordPress 文章可以设置多个分类,但当你选择多个层级的分类时,前台可能并不是按照层级递进的顺序来显示,本文解决的就是这个问题。
以下方法是使用了WordPress的Hook,当使用函数 get_the_category()
或 the_category()
的时候会自动按照层级顺序显示分类。
注意: DUX主题已经有此功能。
WordPress 文章设置多个分类时按照层级顺序显示的方法
将以下代码复制到主题文件 functions.php
中
/**
* 文章多个分类时按照层级顺序显示
* https://themebetter.com/wordpress-multi-cat-show.html
*/
add_filter('get_the_categories', 'tba_get_the_categories', 10, 1);
function tba_get_the_categories($categories) {
usort($categories, function ($a, $b) {
return $a->category_parent <=> $b->category_parent;
});
$newArr = array();
$ids = array();
foreach ($categories as $category) {
$ids[] = $category->term_id;
if ($category->parent == 0) {
$newArr[] = $category;
} else {
$index = array_search($category->parent, $ids);
array_splice($newArr, $index + 1, 0, array($category));
array_splice($ids, $index + 1, 0, array($category->term_id));
}
}
return $newArr;
}