I have three level category structure as bellow.

- parent 1
  - parent sub 1
    - child 1
    - child 2
  - parent sub 2
    - child 3
    - child 4

Unfortunately, some of posts doesn't fill correctly which means it ticks only the sub parent level or child level.

I have a specific requirement to get whole category structure by post id. So I used following code to retrieve the ids,

wp_get_post_categories( $post_id )

This is only giving me the category ids which was ticked, but I need the full category structure.

Eg :

if a posts ticked only child 2, from above code I get only child 2 cat id. instead of that I need child 2,parent sub 1 & parent 1 cat ids.

How can I do that ?

1 Answer 1


Have you tried using get_ancestors?

Ideally, you would do this in a hook after the post has been updated and add the parent categories to the post so that you can use them in Queries.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.