get post id using the $query_vars variable

How can I get the ID of a post (or page) based on the $query_vars variable? I want to do something like

$query_vars['post_id']

But I don’t have a reference page that has the list of $query_vars perams. The code will be using the template_redirect action hook.

Related posts

Leave a Reply

2 comments

  1. When viewing a single post, get_the_ID(); used within the loop will return the current post’s ID.

    But I don’t have a reference page that has the list of $query_vars params…

    Dumping it

    global $wp_query;
    var_dump($wp_query->query_vars);
    

    would provide such a reference.

    Where you’d subsequently see that $wp_query->query_vars['page_id'] yields the page ID.

  2. If you’re on a single post or page view, try using get_queried_object_id().

    Or, if you don’t know what type of view you’re on, use get_queried_object() and then analyse the object returned to find out whether its a post, a taxonomy term, or something different.