1

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.

  • global $post; echo $post_id = $post->ID; anywhere will do the job for you. – Mayeenul Islam Nov 22 '15 at 9:04
  • 1
    @MayeenulIslam not true, what about archive pages. And what about a bad query or bad code that changed the $post global – Pieter Goosen Nov 22 '15 at 9:08
  • @PieterGoosen Right. I overlook the header.php portion. :( – Mayeenul Islam Nov 22 '15 at 9:09
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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