如何知道当前类别的子类别是否为空?
我使用下面的代码过滤出没有产品和类别的类别。
$re_child_terms = get_term_children( $term->term_id, \'category\' );
if ( $term->count > 0 || ! empty( $re_child_terms ) ) {
现在想在这里过滤掉空的子类别,有可能吗?怎样如何知道当前类别的子类别是否为空?
我使用下面的代码过滤出没有产品和类别的类别。
$re_child_terms = get_term_children( $term->term_id, \'category\' );
if ( $term->count > 0 || ! empty( $re_child_terms ) ) {
现在想在这里过滤掉空的子类别,有可能吗?怎样你需要在$re_child_terms
大堆根据文件get_term_children 返回一个term\\u id数组,因此您需要在id上循环,获取术语并将其保存到新数组中(如果它们不是空的)。
$re_child_term_ids = get_term_children( $term->term_id, \'category\' );
$re_child_terms = array();
foreach ( $re_child_terms_ids as $child_id ) {
$child = get_term($child_id);
if ( is_object($child) && !($child instanceof WP_Error) ) {
if ( $child->count > 0 ) {
$re_child_terms[] = $child;
}
}
}
if ( $term->count > 0 || !empty($re_child_terms) ) {
// do stuff
}
// note: this code is untested but should work
EDIT (封装到函数中):// in functions.php
if ( ! function_exists ) {
function get_nonempty_term_children( $term_id, $taxonomy ) {
$child_ids = get_term_children( $term_id, $taxonomy );
$child_objs = array();
foreach ($child_ids as $id) {
$child = get_term($id);
if ( is_object($child) && !($child instanceof WP_Error) ) {
if ( $child->count > 0 ) {
$child_objs[] = $child;
}
}
}
return $child_objs;
}
}
// in template
$re_child_terms = get_nonempty_term_children($term->term_id, \'category\');
if ( $term->count > 0 || !empty($re_child_terms) ) {
// do stuff
}
我正在尝试创建一个显示特定类别的所有子类别的页面。所以在上下文中,我有一个标题为“目的地”的父类别。我希望能够点击目的地,并被引导到一个页面,显示子类别或国家的列表。下面是我试图实现的一个示例,减去顶部的地图-https://www.vagabrothers.com/destinations. 在理想情况下,类别页面的布局将与此页面相同。你可以从上面的例子中看出我的意思。它会使网站上的导航像这样:目的地>国家>个人帖子。我正在使用CPT UI,设置了一个名为“目的地”的自定义帖子类型和类别,然