Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I am trying to retrieve the slug of the current wordpress page outside the loop. The title of the page returns with wp_title () but how can I get the slug?

<li><a href="/slug-of-current-page/"><?php wp_title("",true); ?></a></li>
share|improve this question

4 Answers 4

up vote 24 down vote accepted

use global variable $post.

    global $post;
share|improve this answer
Thank you. Your solution works great. Just need to echo the slug: <?php global $post; $post_slug=$post->post_name; echo $post_slug; ?> –  sarytash Feb 13 '12 at 12:13
Like sarytash said, you need to echo it. So, this'd be ideal: <?php global $post; echo $post->post_name; ?> –  its_me Oct 11 '13 at 15:59

Given the code example, it looks like what you really need is a link. In that case, you can use get_permalink(), which can be used outside of the loop. That should do what you need more reliably than using the post slug.

share|improve this answer
This is the full URL though, not just the slug. –  Fred Nov 21 '14 at 15:09

Just further on @Matthew Boynes answer, if you're interested in getting the parent slug (if any) also then I've found this function useful:

function mytheme_get_slugs() {
    if ( $link = get_permalink() ) {
        $link = str_replace( home_url( '/' ), '', $link );
        if ( ( $len = strlen( $link ) ) > 0 && $link[$len - 1] == '/' ) {
            $link = substr( $link, 0, -1 );
        return explode( '/', $link );
    return false;

Eg to add the slug(s) to the body class:

function mytheme_body_class( $classes ) {
    if ( $slugs = mytheme_get_slugs() ) {
        $classes = array_merge( $classes, $slugs );
    return $classes;
add_filter( 'body_class', 'mytheme_body_class' );
share|improve this answer

An alternative to Arvind's solution is to use the sanitize_title function:

In this specific case:

<li><a href="/<?php $slug = sanitize_title( get_the_title(), $fallback_title ); 
echo $slug; ?>/"><?php wp_title("",true); ?></a></li>
share|improve this answer
The slug is editable. A post titled Hello World! may get the slug random-nonsense. –  toscho Feb 13 '12 at 16:36

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.