How to get the slug of a parent page
In WordPress, there are many situations where you need to get the slug of the parent page from a child page. You can easily get the slug of the parent page by using the following method.
$parent_id = $post->post_parent;
$parent_slug = get_post($parent_id)->post_name;
How this code works
First, get the ID of the parent page of the current page with $post->post_parent
. Then, the parent page information is retrieved using get_post($parent_id)
, and the slug of the parent page is retrieved from the post_name
property.
Notes
This code only works if the page is a child page. For top-level pages, post_parent
is 0, so nothing specific is retrieved.
Conclusion
In WordPress, you can easily get the slug of the parent page using the above method. However, it is necessary to implement the code while paying attention to the hierarchical structure of the page.