Get the current page name in WordPress using $pagename

x theme

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 “http://www.example.com“.

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

Related posts:

About the author

admin

Leave a Reply

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