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

3 Answers 3

up vote 15 down vote accepted

use global variable $post.

<?php 
    global $post;
    $post_slug=$post->post_name;
?>
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

You can use get_permalink() outside of the loop, that should do what you need.

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

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
3  
The slug is editable. A post titled Hello World! may get the slug random-nonsense. –  toscho Feb 13 '12 at 16:36

Your Answer

 
discard

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.