Get the correct post id for all post and page in header.php

get_queried_object_id() will return the ID of the current single post or page being viewed, as well as the static front page. For any type of archive page (except date, custom post type and home archives), the following will be returned:

  • Category ID of the category archive being viewed

  • Tag ID of the current tag archive being viewed

  • Author ID of the current author archive being viewed

  • Term ID for the current term page being viewed

If this is not the case in your case, you, your theme or a plugin you are using is in all probability using query_posts somewhere. query_posts breaks the main query object and resets the main query object to the custom query using query_posts. This is why you should never ever ue query_posts