If you are in the loop then the other answers will help you.
If not (for example you are hooking on init
or plugins_loaded
) you can resort to a PHP primitive like parse_url()
.
Here's a function that works in both cases:
function get_the_slug() {
global $post;
$slug = $post->post_name ?? '';
if ( ! $slug ) {
$slug = basename( parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ) );
}
return $slug;
}
Please note that this approach only works on posts/pages at root level, because of how basename()
works.