Join the Voxel Guide Community!

Get Involved

Calculate distance between 2 CPT's with

Description/Instructions

Made this to calculate the distance between a accommodation (CPT) and a list of selected POI’s (other CPT)

Instructions

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
Copy Code

Let's Chat About this Snippet

Chat Toggle
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Voxel Guide AI
Ask me anything about Voxel!
Send
Powered by AI24