Get page ancestors the easy way in WordPress

WordPress is used by a lot of people as a real CMS. Although it is actually a blogging tool, it has a bunch of features that enables it to compete with most real CMSs.

A function that comes in hand while building a website with WordPress but isn’t well documented is get_post_ancestors(). With this function you can get the id’s of the pages that are higher in the page-hierarchy than the current page. This can be used to generate breadcrumbs, or for highlighting the current path a user is following in the navigation, like I do in the navigation on this site.

[sourcecode language=”php”]$ancestors = get_post_ancestors($post);
if(in_array(17, $ancestors)) {
// Code that will be parsed when this page has a ancestor with id 17

By running this function once, you can build a array that contains all ancestors of the current page (or post). After that you can simply check whether or not a page id is in that array and therefor is a ancestor of the current page.

What does this code do?

The example above looks really simple and it actually is. I’ll try to explain it step by step in the following lines so you can use it on your own.

The first line is the actual working of the function get_post_ancestors(). It works with the variable $post that is containing the information about the current page or post. The variable $ancestors will be a array that is filled with the id’s of the pages that are the ancestors of the current page.

[sourcecode language=”php”]$ancestors = get_post_ancestors($post);[/sourcecode]

Now we are able to check if the id that we are looking for is amongst those id’s and that’s what’s happening in line number three with PHP-function in_array().

This function checks if the first value that is provided (17 in this example), is present in the second value (the array $ancestors). If it is, the code in the if-statement will be processed. You can do inside there whatever you like, from highlighting a navigation item, or creating a breadcrumbs path.

[sourcecode language=”php”]if(in_array(17, $ancestors)) {[/sourcecode]

And that’s basically it. There’s more that you can do with this function, but I’ve proven that it’s powerful and it’s very easy to use.

No need for writing your own functions

I’ve seen a lot of people writing their own functions in order to do exactly the same as this function does. But here is no need to do that, since WordPress is perfectly capable of doing this with it’s own functions.

So why should we write a new function?

One reply on “Get page ancestors the easy way in WordPress”

  1. Thank you so much. This post might be a couple of years old but it’s still relevant and saved me lots of coding headaches! 🙂

Comments are closed.