1

on WordPress Developer Resources website's page related to get_the_ID() function it says:

Retrieves the ID of the current item in the WordPress Loop

But I can use it outside of the loop and it works without using get_queried_object_id() which is apparently recommended in such a case.

Why is that?

(little code snippet to let you understand what I mean):

get_header();

echo get_the_ID(); // Shows the id of currently displayed page.

// Here comes the loop!
$some_query_args...
$some_query_loop {
    echo get_the_ID(); // Shows the id of queried page/post.
}

get_footer();

1 Answer 1

4

The get_the_ID() function uses the global $post variable, which outside of the loop is sometimes equal to get_queried_object_id(). Within the loop, the $post variable is set to the current post within the loop.

As to why get_queried_object_id() is recommended outside of the loop, is because it does not use the global $post variable, so is less likely to be corrupted by loops.

2
  • 3
    note that sometimes the queried object might not be a post, e.g. on an author archive or a term archive it might actually be a WP_Term or WP_User object instead of a WP_Post object. get_the_ID will always return a post ID if there is a "current post" though
    – Tom J Nowell
    Commented Jul 30 at 19:24
  • That's amazing, gentlemen!. That basically answers my question.
    – Daniel
    Commented Jul 30 at 19:59

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.