0

想象一下,我有一个这样的 URL 结构: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。

4

1 回答 1

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>';  } 
于 2012-09-14T00:00:52.827 回答