A very useful WordPress code snippet to know…

As I was working on a custom WordPress theme (based on _s) I found myself trying to get the slug of a post to use as a class for additional styling. Unfortunately, WordPress doesn’t have a get_the_slug() function or a the_slug() function. Well, not built out like that at any rate. The “why not?” is basically because the global $post object contains that info and thus can be found already and no extra functions needed. And then I ran into this wonderful bit of code from TCBarret (code commenting is mine):

/*This function gets the slug of a post 
- you need this to use the next code snippet.
*/
function get_the_slug( $id=null ){
  if( empty($id) ):
    global $post;
    if( empty($post) )
      return ''; // No global $post var available.
    $id = $post->ID;
  endif;

  $slug = basename( get_permalink($id) );
  return $slug;
}

So again, the above code will get_the_slug();. Now to use it, we want a filter and echo out the filtered post ID as the_slug(). And that code is:

/*This adds a filter and allows us to display the results of the
get_the_slug() function noted above.
*/
function the_slug( $id=null ){
  echo apply_filters( 'the_slug', get_the_slug($id) );
}

How to use this? Well I decided to build out a little utility plugin which incorporates the above code so I can use it pretty much in any WordPress install – it’s not tied to a theme or what not. You can use the above code in a theme’s functions.php instead of a plugin but I think a plugin is a better choice as it means the functionality is usable across whatever theme you decide to use. Anyway, special thanks to TCBarret for his excellent (and very useful) code.