Wordpress - How do I retrieve the slug of the current page?

Use the global variable $post:

<?php 
    global $post;
    $post_slug = $post->post_name;
?>

As per other answers, slug is stored in the post_name property. While it could be accessed directly, I prefer the (underused) get_post_field() function for accessing post properties which have no proper API for them.

It requires post provided explicitly and doesn't default to the current one, so in full for the current post it would be:

$slug = get_post_field( 'post_name', get_post() );

EDIT 5 APRIL 2016

After digging for more reliability, I ended up doing this answer to the following post which leads to this edit: (Be sure to check it out)

  • $GLOBALS['wp_the_query'] vs global $wp_query

The most reliable method till date I could come up with is the following:

// Get the queried object and sanitize it
$current_page = sanitize_post( $GLOBALS['wp_the_query']->get_queried_object() );
// Get the page slug
$slug = $current_page->post_name;

This way, you are 99.9999% sure that you get the correct data every time.

ORIGINAL ANSWER

Another safer alternative to this problem is using get_queried_object() which holds the current queried object to get the page slug which is held by the post_name property. This can be used anywhere in your template.

$post can be used, but it can be unreliable as any custom query or custom code can change the value of $post, so it should be avoided outside of the loop.

Using get_queried_object() to get the current page object is much more reliable and is less likely to be modified, unless you are using the evil query_posts which breaks the main query object, but then that is all up to you.

You can use the above as follow

if ( is_page() )
    $slug = get_queried_object()->post_name;

Tags:

Slug

Post Meta