EDIT 5 APRIL 2016
After digging for more reliability, I ended up doing this answerthis answer to the following post which leads to this edit: (Be sure to check it out)
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;