How to Get the Current Page ID Inside a Widget

Here’s a quick tip on how to get the current page ID inside a WordPress widget (outside of The Loop).

With WordPress sometimes you’re not always coding inside The Loop.

Using this little hack allows your widgets to grab the current page ID and could be used to set contextual information which isn’t always easy in WordPress.

Of course it can be used in other parts of your WordPress template too such as footers and asides.

[code language=”php”]<?php // Get Current Page ID outside Loop
global $wp_query;
$post_obj = $wp_query->get_queried_object();
$Page_ID = $post_obj->ID;
echo $Page_ID;
?>[/code]

About Wil

Wil is a professional web developer with a passion for leading edge technologies, security and server architecture. He spoke at WordCamp Sydney 2012, co-organizes the WordPress Sydney meetup, is on the sub-committee for WordCamp 2014 and contributes to the WordPress Core development. He likes pizza, sausages, chilies, beer, red wine and hyperdimensional physics.

  • http://dstefaniak.co.uk/ Damian Stefaniak

    thanks for the tip Wil!