Created
January 28, 2019 21:34
-
-
Save fburatti/d1cc6426f9561907c19c7615356716ef to your computer and use it in GitHub Desktop.
Open street map with ACF
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function properties_map_script() { | |
wp_register_style( | |
'leaflet', | |
"https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css", | |
array(), | |
null | |
); | |
wp_register_script( | |
'maps-api-key', | |
'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js', | |
null, | |
null, | |
true | |
); | |
wp_register_script( | |
'maps-api-script', | |
get_template_directory_uri() . "/js/open-street-map-script.js", | |
array('jquery'), | |
null, | |
true | |
); | |
if (is_singular( 'property' ) || is_post_type_archive( 'property' )) { | |
wp_enqueue_script( 'maps-api-key' ); | |
wp_enqueue_script( 'maps-api-script' ); | |
wp_enqueue_style( 'leaflet' ); | |
if (is_singular( 'property' ) ) { | |
$map_data[] = get_property_map_data(); | |
} else { | |
$map_data = get_all_properties_map_data(); | |
} | |
wp_localize_script( 'maps-api-key', 'properties', $map_data ); | |
} | |
} | |
add_action( 'wp_enqueue_scripts', 'properties_map_script' ); | |
function get_property_map_data( $post_id = null ) { | |
global $post; | |
$post_id = is_null($post_id) ? $post->ID : $post_id; | |
// ACF OPEN STREET MAP FIELD | |
$location = get_field('property_map', $post_id); | |
$thumb_attr = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'thumbnail'); | |
return array( | |
'title' => get_the_title( $post_id ), | |
'lat' => isset($location['lat']) ? $location['lat'] : '42.741222', | |
'lng' => isset($location['lng']) ? $location['lng'] : '12.738521', | |
'thumb' => $thumb_attr[0], | |
'url' => get_the_permalink( $post_id ) | |
); | |
} | |
function get_all_properties_map_data($taxonomy = null) { | |
if ( false === ( $loop = get_transient( 'map_properties' ) ) ) { | |
$args = array( 'posts_per_page' => -1, 'post_type' => 'property', ); | |
$loop = get_posts( $args ); | |
set_transient( 'map_properties', $loop, 4 * HOUR_IN_SECONDS ); | |
} | |
$map_data = array(); | |
foreach ( $loop as $post ) : setup_postdata( $post ); | |
$map_data[] = get_property_map_data( $post->ID ); | |
endforeach; | |
wp_reset_postdata(); | |
return $map_data; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment