Get the current page name in WordPress using $pagename

x theme
(Last Updated On: July 10, 2014)

Following is a code snippet to get the current page name in WordPress using $pagename. The global variable $pagename is in the wp-includes/theme.php, and you can find inside get_page_template() function.

$pagename variable is called before your page theme files are execute.

When you should use $pagename WordPress global variable?

1. The variable is only set if you use permalinks. Otherwise it won’t work.
2. It won’t work if you use the page as a static front page (Simple logic). Because as a front page, URL is ““.

Here is the code:

$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;

About the author


Leave a Reply

Your email address will not be published. Required fields are marked *