How can I get the ID of the current post/page/category in a way that matches the ID I get from menus using get_post_meta( $item->ID )['_menu_item_object_id'][0]? I intend to use it in a JavaScript function.

  • For pages, including the Posts Page, it is the page ID
  • For categories, it is the category ID

I have tried using global $wp_query; echo $wp_query->post->ID;, but it gives the ID of a post for category pages and the Posts Page. (first or last displayed post, depending on whether it is before or after the loop)

More info:

I add the last modified date and ID to menu items as data attributes from this question and want to save the last visit date to localstorage, keyed with the ID from the menu so I can compare them.

  • I do not understand the question. What are you trying to do exactly? Give us an example.
    – bynicolas
    Commented May 25, 2017 at 0:42

2 Answers 2


Use get_queried_object_id() to get the ID regardless of what type of object it is- term, post, page.

There is also the get_queried_object() function, which will give you more details, but will have some structural differences depending on object type.

  • get_queried_object_id() still returns the first post for the Posts Page, so I ended up using get_queried_object()->ID, falling back to get_queried_object()->cat_ID or get_queried_object_id() Commented May 25, 2017 at 18:45

This should do it...

global $post;
echo $post->ID;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.