仅显示顶级类别的孩子

时间:2012-09-13 21:23:17

标签: wordpress categories

想象一下,我有这样的网址结构:www.domain.com/category/subcategory /

这是我的代码:

<?php
$args=array(
    'child_of' => $cat-id,
    'hide_empty' => 0,
    'orderby' => 'name',
    'order' => 'ASC'
);
$categories=get_categories($args);
foreach($categories as $category) { 
    echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';  } 
?>

当我在“www.domain.com/category/”时,代码会正确显示该类别的所有子项,但在“www.domain.com/category/subcategory/”上时,代码不会显示任何结果,因为子类别没有任何孩子。我需要代码只显示顶级类别的子代,即使在它的子页面上也是如此。

我如何做到这一点? TIA。

1 个答案:

答案 0 :(得分:0)

$ancestors = get_ancestors($cat-id, 'category');
$args=array(
    'child_of' => ($ancestors ? end($ancestors) : $cat-id), //If category has ancestors, use the top-most ancestor, otherwise, use the current category ID
    'hide_empty' => 0,
    'orderby' => 'name',
    'order' => 'ASC'
);
$categories=get_categories($args);
foreach($categories as $category) { 
    echo '<a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>';  }