Get Post Slug in WordPress

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:

  1. WordPress, stop changing my HTML code!
  2. Display the Latest Posts with WordPress

Comments

  1. Dave says:

    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?

  2. Ray says:

    Absolutely brilliant. I searched for this for half an hour before I read your post and it works perfectly. Thank you!

  3. Trevor says:

    Great approach! Super simple. I like it.

  4. mark says:

    Thank you Josh, works great!

  5. AJ Clarke says:

    Well this is definately a nice and easy way to do it. Thank you very much.

  6. Joseph says:

    Nice approach. Very clever. Thanks for posting it!

  7. 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

  8. Erin says:

    Slick solution. Thanks a ton!

  9. Brian says:

    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.

  10. lazysand says:

    It’s so cool! :D

  11. Michelle Rupisan says:

    You saved me Josh :) thanks very brilliant

  12. justin says:

    Thank you so much! I have been looking for this for over a day. Thank you!

Speak Your Mind

*