basename( get_permalink($id) );

If you have access to the data through the global variable $post you can simply use $post->post_name;

1
2
3
4
5
6
7
8
9
10
11
12
function get_slug( $id = NULL ) {
 
   if( $id != NULL ) {
     return basename( get_permalink($id) );
   }
 
   global $post;
   if( empty($post) ) return;
 
   return $post->post_name;
 
}

In other cases maybe you don’t have the $id and you are trying to get the $post var to early like in an init hook, in this case you can try using url_to_postid to retrieve the ID and then get the slug.

So the full function would be:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function get_slug( $id = NULL ) {
 
  if( $id == NULL ){
 
    global $post;
 
   if( !empty( $post )) {
        $id = $post->ID;
    } else {
        $id = url_to_postid( "http://".$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
    }
 
  } // if $id NULL
 
  return basename( get_permalink($id) );
}
How to get the post slug

Leave a Reply

Your email address will not be published. Required fields are marked *