2 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超5個贊
請嘗試以下代碼,它可以幫助您了解邏輯,您可以根據(jù)需要對其進(jìn)行修改以滿足您的輸出要求
$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貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超4個贊
我設(shè)法找出了這個問題的解決方案!這是經(jīng)過測試并產(chǎn)生我想要的結(jié)果!如果您有更優(yōu)雅的解決方案,請告訴我!
<?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 關(guān)注
- 85 瀏覽
添加回答
舉報