Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
2 views
in Web Technology by (47.6k 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 (106k 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();

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Aug 6, 2019 in Web Technology by Sammy (47.6k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...