+1 vote
1 view
in Web Technology by (29.4k points)

I want to get the page ID before starting the loop in WordPress. I am using

$page = get_query_var('page_id');

Apparently, it returns nothing.

I just want to check a page for its ID and add a class to <body> tag based on it.

1 Answer

0 votes
by (70.6k points)

The reason why WordPress get the Page ID outside the loop is that you're using pretty permalinks, get_query_var('page_id') and it won't work.

You can get the queried object ID by using the following code:-

$page_object = get_queried_object(); 

$page_id = get_queried_object_id(); 

global $wp_query; 

$page_object = $wp_query->get_queried_object(); 

$page_id = $wp_query->get_queried_object_id();

...