user6403246 user6403246 - 6 months ago 29
PHP Question

How can I get id of current page outside loop and using plugin wordpress?

I'm trying to get id of wp current page and read those articles.
get the current page id inside wordpress plugin page
Wordpress Get the Page ID outside the loop.

But all of these answers don't work for me.
Does anybody know how to get id of current page in wp?
If I use the following code

$wp_query->get_queried_object_id()


it gives me this error

Fatal error: Call to a member function get_queried_object_id() on null

Answer

Typically the current page is always available via the globally scoped $post object. You should be able to get the ID of the current page via $post->ID, if you're in a function or method you will just need to define the variable as global by adding global $post; before trying to use it.

There are however exceptions to this, such as automatic pages, such as post type archives, and a large number of the administration pages.

As for your specific error: Fatal error: Call to a member function get_queried_object_id() on null It's saying the $wp_query variable is null you'll either need to add global scope to it via global $wp_query;, or you're trying to use it before it has been defined, in which case you'll need to defer your code via the actions API add_action('some_event', 'your_function');

Update: http://stackoverflow.com/a/3127776/3332022 appears to be a rather concise answer