Skip to main content
1 of 3
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209

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;
Pieter Goosen
  • 55.4k
  • 23
  • 115
  • 209