Since the AJAX can be called from anywhere, even by a search engine, you should pass the ID manually. To do this, you need to include the ID of your current page somewhere in your template.
There is a common practice to include extra information in hidden input
elements. You can add this hidden element to your template file:
<input id="my-post-id" type="hidden" value="<?php echo get_the_ID();?>">
Now, you can get the post’s ID in your AJAX call:
var theID;
theID = jQuery("#my-post-id").val();
This way, you can include this value in your call:
function customFunction() {
var theID;
theID = jQuery("#my-post-id").val();
jQuery.ajax({
type: 'GET',
url: 'AJAX URL HERE',
data: { postid: theID },
// The rest of the AJAX here
}
};
Now, you can check if the ID is set in your Admin-AJAX:
function get_blueprints_for_building () {
// Stop execution if the function is called from out of the page
if (!isset($_GET['postid'])) exit('Please set a post ID!');
$id = $_GET['postid'];
// Now we have the ID!
}
There you go.
Note!
I would also recommend that you use the REST API instead of Admin-AJAX. It’s easier and faster to set up. Take a look at my answer here.
UPDATE
Instead of creating a hidden input, you can also use wp_localize_script
to pass your ID to the script. You need to have an enqueued script though.
wp_localize_script(
'my-js', // The ID of your enqueued JS file
'my_localized_js', // The prefix for object
$my_localized_array // The array that contains your data
);
Now, you can set the ID of the current page in your array:
$my_localized_array = array(
'postID' => get_the_ID,
);
After doing this, you can access your ID in the JS file by using this:
var id = my_localized_js.postID;
Which can be used in the AJAX call later.