get_post_ancestors

函数
get_post_ancestors ( $post )
参数
  • (int|WP_Post) $post Post ID or post object.
    Required:
返回值
  • (int[]) Array of ancestor IDs or empty array if there are none.
定义位置
相关方法
_get_post_ancestorsget_ancestorsget_post_customget_post_classget_post_custom_keys
引入
2.5.0
弃用
-

get_post_ancesters函数用于检索给定文章的所有祖先文章的数组。它只接受一个参数,即文章的ID: 此函数返回的数组包括父文章及其所有父文章。

检索一个文章的祖先的ID。

function get_post_ancestors( $post ) {
	$post = get_post( $post );

	if ( ! $post || empty( $post->post_parent ) || $post->post_parent == $post->ID ) {
		return array();
	}

	$ancestors = array();

	$id          = $post->post_parent;
	$ancestors[] = $id;

	while ( $ancestor = get_post( $id ) ) {
		// Loop detection: If the ancestor has been seen before, break.
		if ( empty( $ancestor->post_parent ) || ( $ancestor->post_parent == $post->ID ) || in_array( $ancestor->post_parent, $ancestors, true ) ) {
			break;
		}

		$id          = $ancestor->post_parent;
		$ancestors[] = $id;
	}

	return $ancestors;
}

常见问题

FAQs
查看更多 >