您可以使用get_categories()
获取数据库中存在的所有类别的详细信息,这样您就可以知道哪些ID是活动类别,哪些不是。正如你所知,默认情况下,get_categories()
将只返回至少包含1篇帖子的类别。通过添加,可以强制显示空类别\'hide_empty\' => true
.
<?php
// identify the current category
$category = get_queried_object();
$categoryId = $category->term_id;
// get all the categories
$allCategories = get_categories(array(
\'orderby\' => \'id\', // order them by their ID
\'order\' => \'ASC\', // counting up
\'parent\' => 0)); // only if it\'s a top-level category
// save first and last IDs, so we only loop through existing categories
$firstId = $allCategories[0]->id;
$lastCategory = end(array_values($allCategories));
$lastId = $lastCategory->id;
// loop to find Next Category - start 1 higher than current ID
for($i = ($categoryID + 1); $i <= $lastId; $i++) {
if(isset($allCategories[$i])) {
$nextCategoryLink = sprintf(
// set up a link
\'<a href="%1$s">%2$s</a>\',
// put the URL into href=""
esc_url( get_category_link( $category->term_id ) ),
// use category name as link text
$category->name
);
// exit the loop so we only have 1 Next
break;
}
}
// loop backwards to find Previous - start 1 lower than current ID
for($i = ($categoryId - 1); $i >= $firstId; $i--) {
if(isset($allCategories[$i])) {
$prevCategoryLink = sprintf(
// set up a link
\'<a href="%1$s">%2$s</a>\',
// put the URL into href=""
esc_url( get_category_link( $category->term_id ) ),
// use category name as link text
$category->name
);
// exit the loop so we only have 1 Previous
break;
}
}
// now, out put the links
// note that if the current category is the first, it won\'t have "prev"
// and if the current category is the last, it won\'t have "next"
if(!empty($prevCategoryLink)) { echo $prevCategoryLink; }
if(!empty($nextCategoryLink)) { echo $nextCategoryLink; }
?>
希望这些评论能引导你完成每一步。