Show map on Vendor page with their location

Hi All,

You probably know that the geolocation plugin is enabled for Vendors, but the visible widget / block is not available, though there have been some requests about it.

With some tweaking it is still possible to use it though. I’ve been digging deep into the WordPress database to find the raw data.
If you’re like me and want to provide a general map of all your vendors, here is a quick-and-dirty solution to output the content as JSON from a PHP file.

<php
//just create a blank page at the root of your website i.e. "/my-data.php"and copy-paste the following 
// Load WordPress context 
if ( !defined('ABSPATH') ) {
    require_once('../wp-load.php' );
}
global $wpdb;

// SQL query to get post_name and meta values for hp_latitude and hp_longitude
//change 'hp_vendor' for 'hp_listing to retrieve all listings. 
$query = "
    SELECT p.post_name, 
           lat_meta.meta_value AS latitude, 
           lng_meta.meta_value AS longitude
    FROM {$wpdb->posts} p
    LEFT JOIN {$wpdb->postmeta} lat_meta 
           ON p.ID = lat_meta.post_id 
           AND lat_meta.meta_key = 'hp_latitude'
    LEFT JOIN {$wpdb->postmeta} lng_meta 
           ON p.ID = lng_meta.post_id 
           AND lng_meta.meta_key = 'hp_longitude'
    WHERE p.post_type = 'hp_vendor' 
          AND p.post_status = 'publish'
          AND (lat_meta.meta_value IS NOT NULL OR lng_meta.meta_value IS NOT NULL)
";

// Execute the query
$results = $wpdb->get_results($query);

// Prepare data for JSON output
$output = [];
foreach ($results as $row) {
    $output[] = [
        'post_name' => $row->post_name,
        'latitude'  => $row->latitude,
        'longitude' => $row->longitude,
    ];
}

// Output the JSON
header('Content-Type: application/json');
echo json_encode($output);

And here is goes :


[{"post_name":"username1","latitude":"43.55395","longitude":"7.017022"},{"post_name":"username2","latitude":"45.889042","longitude":"6.238095"},{"post_name":"username3","latitude":"45.861224","longitude":"6.369137"}]

You just need to call this code from your Google map API.
Check it in action.
I am using Leaflet instead of Google Maps. Supporting Open Source projects and Ukraine.

With a little more effort, you can retrieve the current $post_id from the Vendor page and display it similarly to a Listing, like here.

I could try to pack it in a plugin, whenever I have time, if you feel like it.
But I don’t use OOP, let alone MVC at all. Just cutting to the chase instead.
Contributors welcome. :wink:

2 Likes

The map and the filters above it are just amazing! This is exactly what I need!!! Can you please let me know how you managed to implement the filters above the map? The plugin will be wonderful, just let me know where I need to sign :grinning:

The filters (blue buttons) are just categories.
Suffice to say you have then to filter your json output according to the selected category.

1 Like