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 に答える