I needed to get just the post slug for a project I have been working on. I found several sites that had similar ways of getting the post slug but I came up with an approach that utilizes WordPress’ get_permalink() and PHP’s basename().
The common approach:
$post_obj = $wp_query->get_queried_object();
$post_ID = $post_obj->ID;
$post_title = $post_obj->post_title;
$post_slug = $post_obj->post_name;
My approach:
$slug = basename(get_permalink());
Related posts:
This so very nearly fixed my problem, but I cannot get it to work properly outside of the loop. Is there a way of getting the actual url of the page and stripping it with just php?
Hey Dave, Have you tried passing the ID parameter? It would look something like this, get_permalink(id);
Absolutely brilliant. I searched for this for half an hour before I read your post and it works perfectly. Thank you!
Great approach! Super simple. I like it.
Thank you Josh, works great!
Well this is definately a nice and easy way to do it. Thank you very much.
Nice approach. Very clever. Thanks for posting it!
Thanks for this code, very handy. Just noticed though that the second method doesn’t return the slug if the page / post is the nominated home page, it just returns the root folder. Hope this helps, Charlotte
Slick solution. Thanks a ton!
Just what I was looking for.
I searched long and hard for slug, when it’s post_name and permalink.
How about the temporary permalink when it’s still a draft?
Permalink returns the now permalink version.
It’s so cool!
You saved me Josh
thanks very brilliant
Thank you so much! I have been looking for this for over a day. Thank you!