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.
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.
If you by any means searched this topic because of the post page (index page alternative when using static front page), then the right answer is this:
(taken from Forrst | Echo WordPress "Posts Page" title - Some code from tammyhart)
If you're on a page and this does not work:
you can try to build the permalink manually with PHP so you can lookup the post ID:
It may not catch every possible permalink (especially since I'm stripping out the query string), but you can modify it to fit your use case.
This function get id off a page current.
You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):
And simply do:
I have done it in the following way and it has worked perfectly for me.
First declared a global variable in the header.php, assigning the ID of the post or page before it changes, since the LOOP assigns it the ID of the last entry shown:
$GLOBALS['pageid] = $wp_query->get_queried_object_id();
And to use anywhere in the template, example in the footer.php:
echo $GLOBALS['pageid];