存档页面中的下一个和上一个类别名称和链接仅父级WordPress

时间:2018-01-30 作者:أسامة محمد

how get next and previous category name and link parent only wordpress in archive page我做了很多尝试,但都是通过获取ID并添加1或丢失1来实现的,但这导致了我的错误

1 个回复
SO网友:WebElaine

您可以使用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; }
?>
希望这些评论能引导你完成每一步。

结束

相关推荐

Custom posts - tag pagination

我使用以下代码输出属于tag:add_filter(\'pre_get_posts\', \'query_post_type\'); function query_post_type($query) { if(is_category() || is_tag() && empty( $query->query_vars[\'suppress_filters\'] ) ) { $post_type = get_query_var(\'pos