get_term_children

函式
get_term_children ( $term_id, $taxonomy )
引數
  • (int) $term_id ID of term to get children.
    Required:
  • (string) $taxonomy Taxonomy name.
    Required:
返回值
  • (array|WP_Error) List of term IDs. WP_Error returned if `$taxonomy` does not exist.
定義位置
相關方法
_get_term_childrenget_category_childrenget_childrenget_page_childrenget_term_field
引入
2.3.0
棄用
-

get_term_children: 這個函式檢索一個特定術語的所有子術語的ID陣列。它需要兩個引數:父術語的ID和該術語所屬的分類法的名稱。它返回一個子術語ID的陣列。

將所有術語的子代合併為一個單一的ID陣列。

這個遞迴函式將把$term的所有子項合併到同一個術語ID陣列中。只對有層次的分類法有用。

如果$term在$taxonomy中不存在,將返回一個空陣列。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
function get_term_children( $term_id, $taxonomy ) {
if ( ! taxonomy_exists( $taxonomy ) ) {
return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
}
$term_id = (int) $term_id;
$terms = _get_term_hierarchy( $taxonomy );
if ( ! isset( $terms[ $term_id ] ) ) {
return array();
}
$children = $terms[ $term_id ];
foreach ( (array) $terms[ $term_id ] as $child ) {
if ( $term_id === $child ) {
continue;
}
if ( isset( $terms[ $child ] ) ) {
$children = array_merge( $children, get_term_children( $child, $taxonomy ) );
}
}
return $children;
}
function get_term_children( $term_id, $taxonomy ) { if ( ! taxonomy_exists( $taxonomy ) ) { return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) ); } $term_id = (int) $term_id; $terms = _get_term_hierarchy( $taxonomy ); if ( ! isset( $terms[ $term_id ] ) ) { return array(); } $children = $terms[ $term_id ]; foreach ( (array) $terms[ $term_id ] as $child ) { if ( $term_id === $child ) { continue; } if ( isset( $terms[ $child ] ) ) { $children = array_merge( $children, get_term_children( $child, $taxonomy ) ); } } return $children; }
function get_term_children( $term_id, $taxonomy ) {
	if ( ! taxonomy_exists( $taxonomy ) ) {
		return new WP_Error( 'invalid_taxonomy', __( 'Invalid taxonomy.' ) );
	}

	$term_id = (int) $term_id;

	$terms = _get_term_hierarchy( $taxonomy );

	if ( ! isset( $terms[ $term_id ] ) ) {
		return array();
	}

	$children = $terms[ $term_id ];

	foreach ( (array) $terms[ $term_id ] as $child ) {
		if ( $term_id === $child ) {
			continue;
		}

		if ( isset( $terms[ $child ] ) ) {
			$children = array_merge( $children, get_term_children( $child, $taxonomy ) );
		}
	}

	return $children;
}

常見問題

FAQs
檢視更多 >