Get a post’s ID

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.

<?php
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.

<?php
// start the loop
the_post();

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

// back to normal
rewind_posts();