Export custom post type as json data in wp

, , , , 13/02/2018

The goal : Export all custom post type with acf field like data location in order to create a map with markers (usefull to display large number of marker)

This function will export all of our cusom post type as a json file when admin is saving post :

// export post type as json every time admin is saving post
function export_posts_in_json ($post_id) {

    // execute save_post only for cpt 
    global $post; 
    if ($post->post_type != 'your-post-type'){
        return;
    }
    // set your parameters
    $args = array(
        'post_type' => 'your-post-type',
        'post_status' => 'publish',
        'posts_per_page' => -1,
    );

    $query = new WP_Query( $args );
    $posts = array();

    while( $query->have_posts() ) : $query->the_post();
    
    // select data to store ( here i use also ACF )
    $posts[] = array(
        'title' => get_the_title(),
        'excerpt' => get_the_excerpt(),
        'location' => get_field('carte'),
        'adresse' => get_field('adresse'),
        'cp' => get_field('code_postal'),
        'ville' => get_field('ville'),
        'url' => get_permalink(),
    );

    endwhile;

    wp_reset_query();

    // debug : print_r(dirname(__FILE__));
    
    // encode data beautify code
    $data = json_encode($posts , JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    
    // select the folder where you will put your json
    // create folder : wp-content/themes/your-theme-name/data
    $folder =  dirname(__FILE__) . '/data/';

    // by default file_put_contents will replace the existing file
    // if you don't want then set a date for the file
    // ex : $file_name = date('Y-m-d') . '.json';

    $file_name = 'cpt-name.json';
    file_put_contents($folder.$file_name, $data);
}

add_action( 'save_post', 'export_posts_in_json' );

Retrieve data

Let’s create a loop in order to store data in variables for each ctp post present in json :

Create a div call map :

<div id="map">

 <!--  our php loop start here -->
 <!--  our html template with data variables -->
<!--  the end of the php loop -->

</div>

Create the loop

$str = file_get_contents(dirname(__FILE__) . '/data/cpt-name.json');
$json = json_decode($str, true);              
foreach ($json as $data) {
        $name = $data['title'];
        $lat = $data['location']['lat'];
        $lng = $data['location']['lng'];
        $adresse = $data['adresse'];
        $cp = $data['cp'];
        $ville = $data['ville'];
        $url = $data['url'];
}

Create the template ( remember to use php brackets to include ou template in html )


<div class="marker" data-lat="<?php echo $lat; ?>" data-lng="<?php echo $lng; ?>">
     <div class="meta">
          <p class="caption-name"><a href="<?php echo $url; ?>" rel="bookmark" ><?php echo $name; ?></a></p>
          <p><?php echo $adresse; ?> <br/> <?php echo $cp; ?> - <?php echo $ville; ?></p>
          <p><a class="view" href="<?php echo $url; ?>" rel="bookmark" title="Voir le profil de <?php echo $name; ?>">view</a></p>
     </div>
</div>

And finally in javascript make the magic !

Note : i use google map with markerclusterer library to manage multiple markers on map

<!-- load jquery before -->
<script src="<?php echo get_template_directory_uri(); ?>/js/js-marker-clusterer/src/markerclusterer_compiled.js" type="text/javascript" charset="utf-8"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEY&libraries=places?v=3?sensor=false" type="text/javascript"></script>

    (function($) {
    
        /* This function will render a Google Map onto the selected jQuery element */
        function render_map( ) {
          // var
         var $markers = $('#map').find('.marker');
          // vars
         var options = {
          zoom      : 14,
          center        : new google.maps.LatLng(0, 0),
          mapTypeId : google.maps.MapTypeId.ROADMAP,
          panControl: false,
                zoomControl: true,
                zoomControlOptions: {
                    style: google.maps.ZoomControlStyle.SMALL,
                    position: google.maps.ControlPosition.LEFT_BOTTOM
                },
                mapTypeControl: false,
                scaleControl: true,
                streetViewControl: true,
                streetViewControlOptions: {
                    position: google.maps.ControlPosition.LEFT_TOP
                },
                overviewMapControl: false,
          // styles from https://snazzymaps.com
          styles: [{"featureType":"landscape","stylers":[{"saturation":-100},{"lightness":60}]},{"featureType":"road.local","stylers":[{"saturation":-100},{"lightness":40},{"visibility":"on"}]},{"featureType":"transit","stylers":[{"saturation":-100},{"visibility":"simplified"}]},{"featureType":"administrative.province","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"visibility":"on"},{"lightness":30}]},{"featureType":"road.highway","elementType":"geometry.fill","stylers":[{"color":"#ef8c25"},{"lightness":40}]},{"featureType":"road.highway","elementType":"geometry.stroke","stylers":[{"visibility":"off"}]},{"featureType":"poi.park","elementType":"geometry.fill","stylers":[{"color":"#b6c54c"},{"lightness":40},{"saturation":-40}]},{}]
         };
          // create map             
         var map = new google.maps.Map( document.getElementById("map"), options);
            
          // add a markers reference
            if (map) {
             map.markers = [];
            
               // add markers
             $markers.each(function(){
                
                    add_marker( $(this), map );
                
              });
    
              // center map
             center_map( map );
    
    
                var clusterStyles1 = [
            {
                textColor: 'white',
                url: 'http://your-domain/wp-content/themes/your-theme/img/cluster-reflexologue.png',
                height: 32,
                width: 32,
            },
            {
                textColor: 'white',
                url: 'http://your-domain/wp-content/themes/your-theme/img/cluster-reflexologue.png',
                height: 32,
                width: 32,
            },
            {
                textColor: 'white',
                url: 'http://your-domain/wp-content/themes/your-theme/img/cluster-reflexologue.png',
                height: 32,
                width: 32,
            }
    
        ];
    
        var mcOptions1 = {
            // gridSize: 50,
            styles: clusterStyles1,
            maxZoom: 18,
            // minimumClusterSize : ,
        };
    
            var markerCluster = new MarkerClusterer(map,  map.markers, mcOptions1); 
    
            markerCluster.setCalculator(function (markers) {
    
            return {
                text: '' + markers.length +'',
                index: 1                   
            };
        });
    
        // markerCluster.addMarker(map.markers);  
        //  markerz.setAnimation(google.maps.Animation.DROP);
    
        }
        
        /* This function will add a marker to the selected Google Map */
        function add_marker( $marker, map ) {
          // var
         var latlng = new google.maps.LatLng( $marker.attr('data-lat'), $marker.attr('data-lng') );
         var icon = 'http://your-domain/wp-content/themes/your-theme/img/icons/marker1.png';
          // create marker
            
         var marker = new google.maps.Marker({
          position  : latlng,
          map           : map,
          icon        : icon
         });
            
          // add to array
         map.markers.push( marker );
    
          // if marker contains HTML, add it to an infoWindow
         if( $marker.html() )
         {
          // create info window
          var infowindow = new google.maps.InfoWindow({
       content      : $marker.html()
          });
           // show info window when marker is clicked
          google.maps.event.addListener(marker, 'click', function() {
            infowindow.open( map, marker );
           });
         }
        }
    
        /* This function will center the map, showing all markers attached to this map */
        function center_map( map ) {
          // vars
         var bounds = new google.maps.LatLngBounds();
          // loop through all markers and create bounds
         $.each( map.markers, function( i, marker ){
           // var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
           // bounds.extend( latlng );
                var latlng = new google.maps.LatLng( marker.position.lat(), marker.position.lng() );
                        bounds.extend( new google.maps.LatLng(48.8566140, 2.3522219) ); // lattitude paris
          });
          // only 1 marker?
         if( map.markers.length == 1 )
         {
          // set center of map
             // map.setCenter( bounds.getCenter() );
             // map.setZoom( 14 );
                map.setCenter( bounds.getCenter() );
                        map.setZoom( 7 );
         }
         else
         {
          // fit to bounds
          // map.fitBounds( bounds );
                map.setCenter( bounds.getCenter() );
                        map.setZoom( 7 );
         }
        }
    
        /* document ready : This function will render each map when the document is ready (page has loaded) */
        $(document).ready(function(){
           render_map();
        });
    })(jQuery);