I’ve got a page with a blogroll in the left column and a sidbar in the right one. When I try to retrieve the page-id inside of the sidebar like:
echo $post->ID;
echo get_the_ID();
The result is 3726 but the page URI is page_id=3722 ! I’m really confused now. I badly have to catch the real page id to be able to use custom fields (with the right values).
EDIT:
I just noticed that 3726 is the id of the last blog element being displayed. But how to grab the page id?
There are two ways to get what you need. One is mentioned in Identify the page being shown while in The Loop:
Unfortunately, this might break.
get_queried_object_id()
looks in the global variable$wp_query
for the ID, and that variable can be overwritten during the page rendering byquery_posts()
. The same is true for functions likeis_page()
.But you can fetch the real post ID earlier, during
template_redirect
, store its value, and get it in your widget class.First we need a helper function that collects the post ID for later usage:
And now you can use that value wherever you want, for example in your
widget()
method:Actually get_queried_object_id() should do this trick but it’s not storing the proper page id – like toscho mentioned it might break.
There’s an easy ways around this problem and I always prefer the easiest possible solution. So I came around with this one.
like that:
http://www.mypage.com/examplepage/
and I can use now theuri without the slashes to feed the method
get_page_by_path()
The resulting code:
I’m not sure if it’s possible in WordPress (I’m new to it) to declare two same path names – this might be a weak point of this solution. But so far it works perfectly.