Back
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.
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();
$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();
31k questions
32.8k answers
501 comments
693 users