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?

27 thoughts on “WordPress – the_slug() – Get post slug function

    • Hi Mike.

      Both my methods and yours make us of the global $post object. I’m not sure there would be any significant speed difference between them.

      The only crucial difference I see is that the author may have deliberately mis-matched the slug and the title. Your approach would always return the initially generated default value, not the actual slug. I’m not sure that would match expectations.

      • That’s a good point, my method doesn’t catch when someone manually tweaks the slug.

        Also, it’s not the $post, but do_action that I try to avoid. I know it’s there for plugins to use, but it does grow & then walk an array.

  1. The snippets are really helpful, it saves my time of copy and paste the tag link manually.

  2. I used your snippet on a horizontal scroll based website to create anchors to the posts. I just needed the_slug(); to get it to work.

    On the link:
    <a href="#” title=”” rel=”bookmark”>

    On the post:
    <td class="celula" id="”>

    Good work, thks^^

    • Happy to be of help. Let us know when your site is finished.

  3. Thank you, saved my time. Working well on generic posts but not as expected on custom post types. Made some little modifications to meet my requirements.

    • can you elaborate on your modifications to make it work with custom post types?

    • A bit more on how this was done: (hope this comment works)

      Although I could have edited the function or used the hooks to produce my variable, this works:

      <?php
      $slug = the_slug() ;
      $thepage = substr($slug, 9);
      $shorturl = 'ocurl.org/'.$thepage; ?>

      <p>To protect privacy, social media buttons have been removed. To share, use the shortened URL for this page: <a href=”http://<?php echo $shorturl; ?>”><?php echo $shorturl; ?></a>.</p>

      And on the server for ocurl.org, I added this to the .htaccess:

      RewriteEngine on
      rewritecond %{http_host} ^ocurl.org [nc]
      RewriteRule ^/(.*) http://occupycastlemaine.org/?p=$1 [L,R]

      Alternatively, I could change my 404 page to 404.php, and edit it this way:

      <?php ob_start(); ?>

      <?php header(“HTTP/1.1 404 Not Found”); ?>

      <html>

      <?php

      $redirectURL = “http://occupycastlemaine.org/?p=”;

      $redirectURL .= substr ($_SERVER["REQUEST_URI"], 1);

      ?>

      <meta http-equiv=”REFRESH” content=”1;url=<?php echo $redirectURL?>”>

      </html>

      • It’s pretty cool that you have been inspired by my little function. Thanks for posting this.

  4. Is there a way to update this so that I can grab a slug of a page using its post id? something like this:

    the_slug($post->ID);
    or
    the_slug(3);

    • The get_permalink function can take a post ID, so I would think this would work:

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

      Or if you wanted to make it so that you wouldn’t have to specify the current post ID, you could do this:

      function the_slug($id, $echo=true){
        if(empty($id)) {
          global $post;
          $id = $post-&gt;ID;
        }
        $slug = basename(get_permalink($id));
        do_action('before_slug', $slug);
        $slug = apply_filters('slug_filter', $slug);
        if( $echo ) echo $slug;
        do_action('after_slug', $slug);
        return $slug;
      }

      EDIT: Added code tags

      • I forgot to follow up on this, Perhaps I should re-visit this popular function.

  5. I’ve been using the following:

    // Get post slug
    function get_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return $slug;
    }

    // Echo post slug
    function the_slug() {
    $post_data = get_post($post->ID, ARRAY_A);
    $slug = $post_data['post_name'];
    return _e($slug);
    }

    I forget where I grabbed these from but you could probably combine them if you preferred it to be in one function. I just wanted to keep with the WordPress ethos of “get” and “the”.

  6. Nice. Using this for adding id and href combined, for use in scrolling category page. Great little function, now a firm resident in all my function files. Thanks

  7. Oops! I posted under the wrong WordPress.com user account. This is really me! Please delete the previous post.

    Thank you so much! I am using a theme (http://wpjumpstart.com) which has Twitter Bootstrap integrated with it. The great thing about Twitter Bootstrap is that it has a Responsive Modal window (http://www.themeblvd.com/demo/jumpstart/features/shortcodes/small-components/).

    I created a directory for a client using Gravity Form submissions to generate post using a custom post type. On the post grid page, I wanted the directory entries to open in a modal window instead of go to the single post page. Using your function, I could use the_slug for the div ID to pass to the modal window. Worked perfectly! Yay!

  8. Thanks for sharing your work Tom. This was the only place on the web I could find how to spit out the slug. And yes, I’m one of those folks who purposely mismatchs my slugs all the time so other hacky approaches would not work.

  9. Pingback: Get post slug function « PixelPress Wiki

Comments are closed.