About a week ago, someone commented on my post about styling top-level pages differently in WordPress, asking how to get the slug for a top-level page while one of its descendant pages is being viewed.
It just so happened that I was in the process of working on a WordPress theme that needed to display the title of the top-level page on all of its descendants. As part of that process, I wrote a quick function that retrieves the top-level parent of any page on a WordPress site as a WordPress post object.
The function is written like:
function get_topLevel($current_post=NULL) {
if(empty($current_post)) { global $post; $current_post = clone $post; }
if(empty($current_post->post_parent)) { return $current_post; }
while(!empty($current_post->post_parent)) {
$current_post = get_post($current_post->post_parent);
}
return $current_post;
}
To use the function in your theme, simply copy the code above and paste it into your functions.php file. Then, you would call the function like:
$topLevel = get_topLevel(clone $post);
Then, if you need to get the slug of that page, you can do one of two things:
- Use the post_name property of the $topLevel object you just accessed. The post_name property is supposed to be an alias of the post slug, according to the quick reference for the WordPress post object on RazorLight Media’s website.
- Use a custom function to retrieve the slug from the permalink (example below).
Getting a Post’s Slug from Its Permalink
To get a post or page slug from its permalink in WordPress, you would normally use code similar to the following.
$permalink = get_permalink( $post->ID ); /* Retrieve the permalink */
$slug = basename( $permalink ); /* Get the slug from the permalink */
Of course, to make things more efficient, you could simply combine the basename()
function and the get_permalink()
function into one action like the following.
$slug = basename( get_permalink( $post->ID ) );
The basename()
function is a native PHP function that strips all information except for the file or directory name from a URI. If you combine it with the WordPress get_permalink()
function, it will, in effect, return the post or page slug.
Post Your Comment