Reputation: 17
I'm trying to get the 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 the id of the 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
Upvotes: 1
Views: 3162
Reputation: 198
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: https://stackoverflow.com/a/3127776/3332022 appears to be a rather concise answer
Upvotes: 2