The WP global variable $pagename should be available for you, I have just tried with the same setup you specified.
$pagename is defined in the file wp-includes/theme.php, inside the function get_page_template(), which is of course called before your page theme files are parsed, so it is available at any point inside your templates for pages.
EDIT:
-
Although it doesn’t appear to be documented, the
$pagenamevar is only set if you use permalinks. I guess this is because if you don’t use them, WP doesn’t need the page slug, so it doesn’t set it up. -
$pagenameis not set if you use the page as a static front page. -
This is the code inside /wp-includes/theme.php, which uses the solution you pointed out when
$pagenamecan’t be set:$pagename = get_query_var('pagename');
if ( !$pagename && $id > 0 ) {
// If a static page is set as the front page, $pagename will not be set. Retrieve it from the queried object
$post = $wp_query->get_queried_object();
$pagename = $post->post_name;
}
NOTE: This answer was originally posted at StackOverflow.com by AJJ
- Martha answered 15 years ago
- last active 15 years ago