
Hierarchical structure of custom post type “Book” (for example).
When we are on Post 2-95
, I want to know:
- Does the post has this post ancestor(
Post 1-31
)?
- Does it have child posts(
Post 3-19
, Post 3-10
)?
Then, if it has:
- an ancestor post: retrieve (object) of this post.
- a child posts: retrieve (objects) of these posts.
Given a post represented by a post object $p
, you can find out if post 31 is the parent via:
if($p->post_parent == 31){
// it is!
} else {
// it isn't
}
To figure out the children, something like:
$posts = get_posts(array(
'post_parent' => $p->ID,
'post_type' => $p->post_type
));
// if there are children, they will be contained in `$posts`
Finally, to determine how many levels deep down the hierarchy you are, you will need to recurse up the hierarchy $p->parent_post == 0
, and then count how many times you needed to do that.
e.g.
$level = 1;
while($parent->parent_post != 0){
$level++;
$parent = get_post($parent->parent_post);
}