Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How To Create Custom WordPress Ajax Endpoint That Works For Both Admins and Visitors
<?php
// Add wp_ajax_ and wp_ajax_nopriv_ actions
add_action('wp_ajax_locations', 'wp_ajax_get_locations');
add_action('wp_ajax_nopriv_locations', 'wp_ajax_get_locations');
// Get locations function
function wp_ajax_get_locations(){
// Latitude and longitude (defaults to Dayton, Ohio)
$lat = isset($_POST['lat']) ? $_POST['lat'] : 39.758949;
$lng = isset($_POST['lng']) ? $_POST['lng'] : -84.191605;
// Query all locations
$locations = new WP_Query([
'post_type' => 'location',
'numberposts' => -1,
'posts_per_page' => -1,
]);
// Locations JSON array
$locations_json = [];
if($locations->have_posts()){
while($locations->have_posts()){
$locations->the_post();
// Get custom ACF fields
$title = get_field('title');
$latitude = get_field('latitude');
$lngitude = get_field('longitude');
$address = get_field('address');
$phone = get_field('phone');
// Create new array location item
$locations_json[] = [
'title' => $title,
'latitude' => (float) $latitude,
'longitude' => (float) $lngitude,
'address' => $address,
'phone' => $phone,
];
}
} wp_reset_postdata(); wp_reset_query();
// Order the locations from closest to furthest based on user latitude and longitude
usort($locations_json, function($a, $b) use ($lat, $lng){
return pow($a['latitude'] - $lat, 2) + pow($a['longitude'] - $lng, 2)
> pow($b['latitude'] - $lat, 2) + pow($b['longitude'] - $lng, 2) ? 1 : -1;
});
// Echo the JSON
header('HTTP/1.1 200 OK');
header('Content-Type: application/json');
echo json_encode($locations_json);
// Be sure to stop execution afterward.
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.