How do I get a post's ID? I know I can use the_ID(), but I have to use it in The Loop. How can I get the post's ID without the loop? Because I think using the loop just to find the post's ID will slow down my script. Maybe i'm wrong. Please help me :)

Thank you!


If you're on a singular page, sometime after init and all the query variables have all ben set up you can use get_queried_object_id or get_queried_object.

if (is_singular()) {
    $post_id = get_queried_object_id();

    // or get the whole object
    $post = get_queried_object();

    // or do the first one differently
    $post_id = get_queried_object()->ID;

You can also just "false start" the loop and get what you need. It probably won't slow down your script: WordPress fetchs all the queried posts at once, so the database hit has already happened. You might use this if you're not a singular page and need to get the first post's ID.

// start the loop

// get the ID
$post_id = get_the_ID();

// back to normal
  • Thank you! Where is the documentation for your first answer? I can't find that in the wordpress codex.. – user25893 Jan 18 '13 at 21:29
  • You can look up the fucntion themselves in the codex, but the codex is not a tutorial site: it's up to you glue everything together. – chrisguitarguy Jan 18 '13 at 22:18

If you already have the post object saved as a variable somewhere (I assume that this is the case) you can get it's ID by $you_post_object->ID. If this is not the case then you should post some of your code so that we know what you are dealing with.

  • I don't have a post object saved in a variable (I don't know what is a post object or how to create one). And what do you mean post some of my code? All I need is to put the post ID in a variable ex: $id = get_the_ID(), but to use this function, I need to put it in a loop, and I don,t know if this is the good way to do it. – user25893 Jan 18 '13 at 20:42

Your Answer

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