Skip to main content
included test function
Source Link

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.

If you are in the loop then the other answers will help you.

If instead you are out of the loop (for example you are hooking on the init or plugins_loaded actions), you can resort to a PHP primitive like parse_url():

$post_slug = basename( parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ) );

Please note that this approach only works on posts/pages at root level.

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.

Source Link

If you are in the loop then the other answers will help you.

If instead you are out of the loop (for example you are hooking on the init or plugins_loaded actions), you can resort to a PHP primitive like parse_url():

$post_slug = basename( parse_url( $_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH ) );

Please note that this approach only works on posts/pages at root level.