Back

Explore Courses Blog Tutorials Interview Questions
+1 vote
1 view
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)
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.7k users

Browse Categories

...