Skip to content

Snippets / PHP

PHP

Calculate distance between 2 CPT's with

J jan.barendse · 164 views · Updated 2 years ago
Made this to calculate the distance between a accommodation (CPT) and a list of selected POI's (other CPT)
I am using it as this in a dynamic tag:<strong>[distance_shortcode lata="@post(location.lat)" lona=" @post(location.lng) " latb="@post(belongstolocation.distances.location.lat)" lonb="@post(belongstolocation.distances.location.lng)"]</strong> to @post(belongstolocation.distances.text), the nearest @post(belongstolocation.distances.selectpoi.value)
// Register shortcode
add_shortcode('distance_shortcode', 'distance_shortcode_function');

// Shortcode function
function distance_shortcode_function($atts) {
// Extract shortcode attributes
$atts = shortcode_atts(array(
'lata' => '',
'lona' => '',
'latb' => '',
'lonb' => '',
), $atts, 'distance_shortcode');

// Convert text values to numbers if they're not empty
$lata = !empty($atts['lata']) ? (float) $atts['lata'] : '';
$lona = !empty($atts['lona']) ? (float) $atts['lona'] : '';
$latb = !empty($atts['latb']) ? (float) $atts['latb'] : '';
$lonb = !empty($atts['lonb']) ? (float) $atts['lonb'] : '';

// Check if all coordinates are provided and numeric
if ($lata !== '' && $lona !== '' && $latb !== '' && $lonb !== '') {
// Calculate distance using Haversine formula
$distance = haversineDistance($lata, $lona, $latb, $lonb);
return round($distance, 2) . " km's";
} else {
return "Please provide valid latitude and longitude for both points.";
}
}

// Function to calculate distance using Haversine formula
function haversineDistance($lat1, $lon1, $lat2, $lon2) {
$earthRadius = 6371; // Radius of the Earth in kilometers
$deltaLat = deg2rad($lat2 - $lat1);
$deltaLon = deg2rad($lon2 - $lon1);
$a = sin($deltaLat / 2) * sin($deltaLat / 2) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * sin($deltaLon / 2) * sin($deltaLon / 2);
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
$distance = $earthRadius * $c;
return $distance;
}
PHP · 39 lines

Discussion 1

Ask a question or share how you used this.

Log in to join the discussion.
gabrielvb 1 year ago

Can this snippet calculate the distance between the user is viewing the CPT, and the CPT? For example, in the doctor template, the user is seeing a doctor, and the template shows something like: this doctor is 10 miles away from you. Something like this. Since the current user has a profile that is a CPT.

jan.barendse 1 year ago

hi Gabriel, between 2 cpt’s yes, maybe even from the actual currentl location of the user, its not an incredible difficult code

Voxel Guide assistant
Ask about snippets, addons & how-tos

Hey — how can I help?

I can dig through the library for snippets, addons, and tutorials.

AI can be wrong — double-check anything important.