W e b I n s i g h t s .

經由 post id 取得最上層與最底層 term id

經由 post id 取得最上層與最底層 term id

WordPress 核心並不提供藉由 Post id 取得最上層與最下層 term id 的函式,在這裡提供兩個函式來讓大家參考:

藉由Post id 來取得最上層term id

/**
* Get top level term id from a post id
*
* @param int $post_id post id
* @param string $taxonomy taxonomy
* @return int
*/
function get_top_level_term_id( $post_id, $taxonomy ) {

$terms = wp_get_post_terms( $post_id, $taxonomy );

$term = $terms[0];
$term_id = $term->term_id;

while( $term->parent ) {
$term_id = $term->parent;
$term = get_term_by( ‘id’, $term_id, $taxonomy );
}
return $term_id;
}

藉由Post id 來取得最底層term id

/**
* Get last child term id(s) from a post id
*
* @param int $post_id post id
* @param string $taxonomy taxonomy
* @param bool $multiple array or single term id
* @return mixed
*/
function get_last_child_term_id( $post_id, $taxonomy, $output_single = false ) {

$terms = wp_get_post_terms( $post_id, $taxonomy );

$new_terms = array();

foreach( $terms as $term ) {
$i = 0;
$new_term = $term;
while( $term->parent ) {
$term_id = $term->parent;
$term = get_term_by( ‘id’, $term_id, $taxonomy );
$i++;
}
if( $output_single ) {
$new_terms[$i] = $new_term;
} else {
$new_terms[$i][] = $new_term;
}
}

$array_last_index = count( $new_terms ) – 1;

$terms = $new_terms[$array_last_index];

if( $output_single ) {
$term = $terms;
$term_id = $term->term_id;
return $term_id;
} else {
$term_ids = array();
foreach( $terms as $term ) {
$term_ids[] = $term->term_id;
}
return $term_ids;
}

}

文章最後更新於 : 2019/07/22