WordPress – the_slug() – Get post slug function

There is no template function (like the_title()) to get the slug of the current post.

There are two ways to do it:

1. Using basename() and get_permalink() to retrieve post slug.


  echo( basename(get_permalink()) ); 

2. Using global $post object to retrieve post slug.

<?php global $post; echo $post->post_name; ?>

I chose the former and added some hooks

3. Fully hookable function to retrieve the post slug

function the_slug($echo=true){
  $slug = basename(get_permalink());
  do_action('before_slug', $slug);
  $slug = apply_filters('slug_filter', $slug);
  if( $echo ) echo $slug;
  do_action('after_slug', $slug);
  return $slug;
}

This provides you with a simple way retrieve and display the post slug. I find this useful for applying unique CSS ids and classes to my HTML mark up.

<div id="some-post-container-<?php the_slug();?>">
 Lorem whatsit here
</div>

I’d love to hear what you use it for!

UPDATE

I’ve posted an update to this function – how to get the slug of your post or page?