下面是如何获取所有顶级类别并循环它们以创建链接列表的方法,
$parent_categories = get_categories( array(
\'fields\' => \'id=>name\', // other term data no needed here
\'parent\' => 0,
));
$parent_category_links = array();
foreach ($parent_categories as $parent_category_id => $parent_category_name) {
$parent_category_links[] = sprintf(
\'<li><a href="%s">%s</a></li>\',
esc_url( get_term_link( $parent_category_id, \'category\' )),
esc_html( $parent_category_name )
);
}
echo \'<ul>\' . implode(\'\', $parent_category_links) . \'</ul>\';
单击上面循环创建的类别链接将使用户转到类别的存档视图(
category.php/archive.php/index.php),在那里可以显示子类别的列表。就像这样,$child_categories = get_categories( array(
\'fields\' => \'id=>name\', // other term data no needed here
\'parent\' => get_queried_object_id(), // you should check that current object is a WP_Term, if you\'re using generic archive or index template
));
if ( $child_categories ) {
$child_category_links = array();
foreach ($child_categories as $child_category_id => $child_category_name) {
$child_category_links[] = sprintf(
\'<li><a href="%s">%s</a></li>\',
esc_url( get_term_link( $child_category_id, \'category\' )),
esc_html( $child_category_name )
);
}
echo \'<ul>\' . implode(\'\', $child_category_links) . \'</ul>\';
} else {
// The Loop to display posts
}
上述代码是一个简化的示例,您应该对其进行修改,以符合您的确切需要和设置
P.s。
get_categories()
返回的数组
WP_Term默认情况下为。要访问术语id,应使用
$term->term_id
.