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

I want to get the current post/page id outside the loop (in header.php) and use this id for Advanced Custom Fields plugin to get the fields.

But i cant get the correct id from front page, archive page(tag, author, category…etc).

Here is the code

if ( is_singular( 'post' ) ) {
  $post_id = $wp_query->post->ID;
  echo 'post id' . $post_id;
} elseif ( is_shop() ) {
  $post_id = get_option( 'woocommerce_shop_page_id' );
  echo 'post id' . $post_id;
} else {
  $post_id = get_queried_object_id();
  echo 'post id' . $post_id
}

One more question, any better method to get the id for all of the page outside loop? I just worry my code is still miss some of the page type.

1 Answer
1

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

Leave a Comment