Beware this content is over 6 years old and considered stale. It may no longer be accurate and/or reflect the understanding of the author but remains here for reference only. Please keep this in mind as you use this content.

I’ve been doing a little more WordPress (v2.9.2) hacking as a new project required a little more CMS-like control over a website than WordPress by default provides.

As a result I’ve resorted to extending WordPress and the results have been pretty encouraging already. I have to say, for the record, that the WordPress team has made extending the WordPress platform a breeze through custom plug-ins and hooks.

OK. Enough WordPress appreciation and on to the reason for the post.

I recently needed a quick and easy way to get the slug for a post parent.

The site I’m working on has a series of sub/mini-sites under the root directory, meaning that there will be multiple homepages for each of the sub-sites and each sub-site will have it’s own navigation options.

As a result, I needed a quick way of determining which sub-site a home slug returned for the current page belonged to. Now, the way I had structured the pages in WordPress was by creating a separate home page for each sub-site as a page of the root site so the URL’s would be:

1
2
3
[root directory] https://artofsimplicity.co.uk/
[sub-site 1] https://artofsimplicity.co.uk/sub-site-1/home/
[sub-site 2] https://artofsimplicity.co.uk/sub-site-2/home/

The way I went about doing this was to retrieve the slug for the parent page, which would either return sub-site-1 or sub-site-2.

Achieving this was quite straightforward with the following snippet of PHP code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Retrieve the page slug.
function get_post_slug($post_parent = false) {
global $post; // WordPress global $post
if ($post_parent) {
$parent = get_post($post_parent, OBJECT); // get the post data.
$slug = $parent->post_name; // get the post_name/slug
} else {
// If not a post_parent the post_name/slug for the
// current page will already be accessible.
$slug = $post->post_name;
}
return $slug;
}
// Same function as above but wrapped up in a new function for convenience.
function get_post_parent_slug() {
global $post; // WordPress global $post
// Once the current post data is loaded you can retrieve
// the post_parent ID to retrieve that posts post_name/slug.
return get_post_slug($post->post_parent);
}

Maybe this simple little snippet will help those trying to achieve a similar effect in WordPress.

At the time of writing WordPress 3.0 has just been released so we’ll see if it’s no longer needed in new version.