2 回答

TA贡献1821条经验 获得超5个赞
请尝试以下代码,它可以帮助您了解逻辑,您可以根据需要对其进行修改以满足您的输出要求
$post = get_post(); // If $post is already available, skip.
$terms = get_the_terms( $post->ID, 'category' );
$outputparent = $outputchild = array();
foreach( $terms as $term ) :
if( $term->parent === 0 ) :
$outputparent[] = '<a href="' . esc_url( get_term_link( $term ) ) .
'" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) .
'</a> ';
else :
$outputchild[] = '<a href="' . esc_url( get_term_link( $term ) ) .
'" title="' . esc_html( $term->name ) . '" ' . '>' . esc_html( $term->name ) .
'</a>';
endif; //Endif
endforeach;
if( !empty( $outputparent ) ) :
echo 'Parent category is checked<br>';
echo implode('<br>', $outputparent);
$outputchild = array();
elseif( !empty( $outputchild ) && empty( $outputparent ) ) :
echo 'Only Childs<br>';
echo implode('<br>', $outputchild);
endif;

TA贡献1816条经验 获得超4个赞
我设法找出了这个问题的解决方案!这是经过测试并产生我想要的结果!如果您有更优雅的解决方案,请告诉我!
<?php
$categories = get_the_terms( $post->ID, 'custom-category' );
// If term is a parent, add to post_parent array.
$post_parent = array();
foreach( $categories as $parent_id ) {
if($parent_id->parent < 1) {
$post_parent[] = $parent_id->term_id;
}
}
// If terms parentId does not exist in post_parent array
// add to array regions as a key => value pair
$regions = array();
foreach( $categories as $category ) {
if (!in_array($category->parent, $post_parent)) {
$regions[$category->term_id] = $category->name;
}
}
// Sort terms based on keys (regions), impolde and print
ksort($regions);
$locations = array();
foreach($regions as $key => $value) {
$locations[] = ' <a href="https://www.google.com/maps?q=' . $value . '">' . $value . '</a>';
}
echo implode(",", $locations);
?>
- 2 回答
- 0 关注
- 86 浏览
添加回答
举报