Often, when using WordPress as a content management or blogging tool on a website, one uses a multi-level page structure. This entails a page being listed “underneath” another page in a tree structure. Usually, if your WordPress installation’s permalinks deviate from the default setting, your page URL structure will look something like this:
http://websiteurl.com/parentpageslug/subpageslug (Note: note a real URL)
What if you require a value to be set depending on the highest level parent page? The process looks like this:
1. Get the permalink for the current page (using the global $post object).
2. Remove the website URL from the string, leaving only the full slug.
3. Split the slug into an array, using the ‘/’ as a separator.
4. The route slug should be at one of the indexes in your array (most likely index 1).
To get the information for the root page, we are going to use a native WordPress function called “get_page_by_path“. To run this function, we will declare it like this:
$root_page = get_page_by_path($root_slug);
This line returns an object (into
$root_page) containing the information for the root page of the page we are currently viewing.
I’ve left points 1 to 4 up to you to work out. Everyone has their own way of coding things. If you know of a smoother or quicker way to achieve the same result, please let me know. 🙂
Thanks guys. I hope you found this quick snippet to be useful. 🙂