假设我有这样一个URL结构:www.domain。com/类别/子类别/
这是我的代码:
<?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。
最合适的回答,由SO网友:helgatheviking 整理而成
好的,试试这个。它应该捕获当前类别对象,然后沿着链向上移动,直到找到当前类别最顶层的祖先。
// get the category object for the current category
$thisCat = get_category( get_query_var( \'cat\' ) );
// if not top-level, track it up the chain to find its ancestor
while ( intval($thisCat->parent) > 0 ) {
$thisCat = get_category ( $thisCat->parent );
}
//by now $thisCat will be the top-level category, proceed as before
$args=array(
\'child_of\' => $thisCat->term_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>\'; }
?>