How can I get the current page name in WordPress?
My approach to get the slug name of the page:
$slug = basename(get_permalink());
The WordPress 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 is called before your page theme files are parsed, so it is available at any point inside your templates for pages.
Although it doesn't appear to be documented, the
$pagename
var is only set if you use permalinks. I guess this is because if you don't use them, WordPress doesn't need the page slug, so it doesn't set it up.$pagename
is 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
$pagename
can't be set:
--
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;
}