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