get_queried_object_id in AJAX

OK, let’s start from trying to understand, what get_queried_object function does. According to its Codex page:

Retrieve the currently-queried object. For example:

  • if you’re on a single post, it will return the post object
  • if you’re on a page, it will return the page object
  • if you’re on an archive page, it will return the post type object
  • if you’re on a category archive, it will return the category object
  • if you’re on an author archive, it will return the author object etc.

As you can see, this function returns the object that should be queried for current request based on the URL of this request.

But AJAX calls are other, independent requests. If you use AJAX API, as you should, then you’re creating a request to wp-admin/admin-ajax.php file. So there is no object queried for that request.

If you need the queried object in your AJAX function, then you have to pass it on in the request you make in JS.

Let’s say, we’re on single post page. The get_queried_object function returns that object. And we want to perform some action with AJAX and we need that post object inside that action. In such case you have to:

  1. Pass the ID of that queried object to JS script.
  2. Use that ID in JS and put it in data that is sent with your AJAX request.
  3. Use that data in your AJAX callback function.