Skip to content

Instantly share code, notes, and snippets.

@chwnam
Created March 3, 2021 04:37
Show Gist options
  • Save chwnam/0a57a8601d72b5dbe85893aca249fba9 to your computer and use it in GitHub Desktop.
Save chwnam/0a57a8601d72b5dbe85893aca249fba9 to your computer and use it in GitHub Desktop.
한 포스트의 중간 텀을 구한다.
/**
* 말단 텀 이외에 찍힌 것 제거
*
* @param int $post_id
* @param string $taxonomy
*
* @return WP_Term[]
*/
function get_mid_terms( int $post_id, string $taxonomy = 'category' ): array {
$terms = wp_get_object_terms( $post_id, $taxonomy );
$terms = array_combine( wp_list_pluck( $terms, 'term_id' ), $terms );
$result = [];
if ( is_array( $terms ) && count( $terms ) > 1 ) {
$parents = [];
$mid_terms = [];
// Build parents links
foreach ( $terms as $term ) {
$parents[ $term->term_id ] = $term->parent;
$ancestors = get_ancestors( $term->term_id, $taxonomy, 'taxonomy' );
if ( $ancestors ) {
for ( $i = 1; $i < count( $ancestors ); ++ $i ) {
$parents[ $ancestors[ $i ] ] = $ancestors[ $i + 1 ] ?? 0;
}
}
}
// Calc mid terms
foreach ( $terms as $term ) {
$p = $parents[ $term->term_id ] ?? 0;
while ( $p ) {
if ( isset( $terms[ $p ] ) ) {
$mid_terms[] = $p;
}
$p = $parents[ $p ] ?? 0;
}
}
// Populate terms
foreach ( array_unique( $mid_terms ) as $term_id ) {
if ( isset( $terms[ $term_id ] ) ) {
$result[] = $terms[ $term_id ];
}
}
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment