Géocoder une adresse au format texte dans un post

Comment géocoder une adresse au format texte dans un post ? Votre solution en 2 clics !

Copiez la ligne de code ci-dessous :

  1. Créer une clé API Google Geocode
  2. Définir 2 champs ACF (un contenant l’adresse au format string et un autre contenant les futures données ACF Maps)
  3. Installer & activer WP Admin OPS et ajouter cette action
  4. Lancer l’action
<?php
/**
 *  WP Admin Ops - Actions
 */
add_filter('wpops/actions', 'wpops_actions');
function wpops_actions($actions) {
​
    $actions[] = array(
        'slug'  => '_pit_post_update_geocode_address',
        'title' => 'POST -> Update geocode address',
        'options' => array(
            array(
                'title' => 'Post status',
                'type'  => 'text',
                'name'  => 'post_status',
                'value' => 'publish',
                'description' => 'Post status to update.'
            ),
            array(
                'title' => 'Post type',
                'type'  => 'text',
                'name'  => 'post_type',
                'value' => 'publish',
                'description' => 'Post type to update.'
            ),
            array(
                'title' => 'Post ID',
                'type'  => 'text',
                'name'  => 'post_id',
                'value' => '',
                'description' => 'Post ID to update.'
            ),
            array(
                'title' => 'Address string meta',
                'type'  => 'text',
                'name'  => 'address_string_meta',
                'value' => '',
                'description' => 'ACF meta key containing address string.'
            ),
            array(
                'title' => 'ACF maps meta',
                'type'  => 'text',
                'name'  => 'acf_maps_meta',
                'value' => '',
                'description' => 'ACF meta key containing geocoded address data.'
            ),
        )
    );
​
    return $actions;
}

/**
 *  WP Admin OPS - Update geocode address
 */
add_action('wp_ajax_wpops__pit_post_update_geocode_address', '_pit_post_update_geocode_address');
function _pit_post_update_geocode_address() {

    $offset                 = (int) $_POST['offset'];
    $options                = (array) $_POST['options'];
    $post_status            = $options['post_status'] ?? 'publish';
    $post_id                = $options['post_id'] ?? '';
    $post_type              = $options['post_type'] ?? '';

    if (!$post_type)
        wp_send_json_error(array(
            'html'  => 'You have to set a "post_type" first.',
            'debug' => print_r($options, true),
            'stop'  => true,
        ));

    $address_string_meta    = $options['address_string_meta'] ?? '';
    $acf_maps_meta          = $options['acf_maps_meta'] ?? '';

    if (!$address_string_meta || !$acf_maps_meta)
        wp_send_json_error(array(
            'html'  => 'You have to set a "address_string_meta" & "acf_maps_meta" first.',
            'debug' => print_r($options, true),
            'stop'  => true,
        ));

    // You need to have a google api key set to "geocode api" in google's console developer
    $google_api_key = $options['google_api_key'] ?? '';

    if (!$google_api_key)
        wp_send_json_error(array(
            'html'  => 'You have to set a "google_api_key" first.',
            'debug' => print_r($options, true),
            'stop'  => true,
        ));
​
    $query_args             = array(
        'post_type'         => $post_type,
        'posts_per_page'    => 1,
        'post_status'       => array($post_status),
        'meta_query'        => array(
            'relation' => 'AND',
            array(
                'key'       => $address_string_meta,
                'compare'   => 'EXISTS',
            ),
            array(
                'key'       => $acf_maps_meta,
                'compare'   => 'NOT EXISTS',
            ),
        ),
    );

    if ($post_id)
        $query_args['post__in'] = array($post_id);

    $post_query = new WP_Query($query_args);
    if (empty($post_query) || !$post_query->have_posts())
        wp_send_json_error(array(
            'html'  => 'No more posts found.',
            'debug' => print_r($post_query, true),
            'stop'  => true,
        ));
​
    if ($post_query->have_posts()) :
        while ($post_query->have_posts()) : $post_query->the_post();
​
        $post_id       = get_the_ID();
        $post_adresse  = get_field($address_string_meta);

        if (!$post_adresse || empty($post_adresse))
            wp_send_json_error(array(
                'html'  => '"address_string_meta" is empty',
                'debug' => print_r($post_id, true),
                'stop'  => true,
            ));

        $post_adresse_url = str_replace(' ', '+', $post_adresse);
        $post_loc_latlng = array();

        try {
            /** Google Geocoder API */
            $geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address=' . $post_adresse_url . '&sensor=false&key=' . $google_api_key);
            $output = json_decode($geocode);

            if (!isset($output->results[0]))
                wp_send_json_error(array(
                    'html'  => 'No results coords found for this address: ' . $post_adresse . '  <a href="' . get_edit_post_link($post_id) . '" target="_blank">Edit Link</a>',
                    'debug' => print_r($post_id, true),
                    'stop'  => true,
                ));

            $post_loc_latlng = array(
                'address' => $post_adresse,
                'lat' => $output->results[0]->geometry->location->lat,
                'lng' => $output->results[0]->geometry->location->lng,
            );
        }
        catch (Exception $e) {
            wp_send_json_error(array(
                'html'  => 'php file get contents issue',
                'debug' => print_r($e, true),
                'stop'  => true,
            ));
        }

        if (!$post_loc_latlng || empty($post_loc_latlng))
            wp_send_json_error(array(
                'html'  => 'can't find lat lng coords for this address: ' . $post_adresse,
                'debug' => print_r($post_loc_latlng, true),
                'stop'  => true,
            ));

        $post_lat      = $post_loc_latlng['lat'] ?? '';
        $post_lng      = $post_loc_latlng['lng'] ?? '';
        
        /** Update acf maps meta */
        update_field($post_id, 'acf_maps_meta', $post_loc_latlng);

        wp_send_json_success(array(
            'html'  => '<br>POST ID: <code>' . $post_id . '</code><br>LAT: <code>' . $post_lat . '</code><br>LNG: <code>' . $post_lng . '</code><br><code>' . ($post_query->found_posts - 1) . '</code> left to go',
            'debug' => print_r($post_id, true),
            'stop'  => false,
        ));

        endwhile; wp_reset_postdata();
    endif;

    wp_send_json_success(array(
        'html'  => 'Posts have been updated.',
        'debug' => print_r($post_query->posts, true),
        'stop'  => true
    ));
}
?>

 

Déclinaison de logo : son importance dans la charte graphique

Site de police d’écriture : notre sélection pour le digital !

WordPress vs Symfony : lequel choisir pour mon projet ?