Feed Leaflet Map with WP_Query() and wp_json_encode()
-
Hello everyone!
I’m working in a wordpress project with two custom post type (documentaries and scenes) and a custom taxonomy (production). Each documentary has many scenes, and I’d like to display a map with all theses scenes in the scene view. So I create two custom fields for scene’s post type: longitude and latitude.
I choose to use Leaflet.js directly, without any plugin. So I enqueued all css and js libraries to my theme, and wrote the following code in a template part, following these instructions from Andy. But this lines brakes my page.
The main idea is to create a new WP_Query() selecting only the scenes which shares the custom taxonomy, iterate throught the results and add an array with desired data (name, url, lng and lat) to a previously defined array called ‘geodata’.
Can some of you review what is wrong please?
<?php /** * @package Illes de futur */ ?> <section id="scene-map"> <div id="map" style="heigth: 440px; border: 1px solid #aaa;"></div> <?php $terms = get_the_term_list( $post->ID, 'production' ); $id = get_the_ID(); $args = array( 'post_type' => 'scene', 'tax_query' => array( 'taxonomy' => 'production', 'field' => 'slug', 'terms' => $terms, ), 'exclude' => $id ); $geodata = array(); $geolocated_scenes = new WP_Query($args); if( $geolocated_scenes->have_posts() ) : while( $geolocated_scenes->have_posts() ) : $geolocated_scenes->the_post(); $geodata[] = [ 'name' => get_the_title(), 'url' => get_post_permalink(), 'lat' => get_post_meta( the_ID(), 'latitude', true ), 'lng' => get_post_meta( the_ID(), 'longitude', true ), ]; endwhile; wp_reset_postdata(); else : ?> <p><?php __('This scene has not geolocation data', 'illles_de_futur'); ?></p> <? endif; echo wp_json_encode( $geodata ); ?> <script type="text/javascript"> var map = L.map( 'map', { center: [20.0, 5.0], minZoom: 2, zoom: 2 }); L.tileLayer( 'https://{s}.mqcdn.com/tiles/1.0.0/map/{z}/{x}/{y}.png', { attribution:'© <a href="https://osm.org/copyright" title="OpenStreetMap" target="_blank">OpenStreetMap</a> contributors | Tiles Courtesy of <a href="https://www.mapquest.com/" title="MapQuest" target="_blank">MapQuest</a><img src="https://developer.mapquest.com/osm/mq_logo.png" width="16" height="16" />', subdomains: ['otile1' , 'otile2' , 'otile3' , 'otile4'] }).addTo( map ); for ( var i=0; i < geodata.length; ++i ) { L.geodata( [geodata[i].lat, geodata[i].lng] ) .bindPopup( '<a href="' + geodata[i].url + '">' geodata[i].name + '</a>' ) .addTo( map ); } </script> </section>
Thanks in advance!!!
- The topic ‘Feed Leaflet Map with WP_Query() and wp_json_encode()’ is closed to new replies.