· 5 years ago · Jun 24, 2020, 01:22 PM
1function bis_listing_location_tag($default_uri, $native_slug, $element, $slug, $native_uri) {
2 global $permalink_manager_options;
3
4 // Use only for "listing" post type & custom permalink
5 if(empty($element->post_type) || $element->post_type !== 'job_listing' || $native_uri) { return $default_uri; }
6
7 if(strpos($default_uri, '%__city%') !== false || strpos($default_uri, '%__state%') !== false || strpos($default_uri, '%__country%') !== false) {
8 // Get location saved with a custom field & API key
9 $listing_location = get_post_meta($element->ID, '_job_location', true);
10 $api_key = (!empty($permalink_manager_options['general']['googleapikey'])) ? $permalink_manager_options['general']['googleapikey'] : '';
11
12 // Do the CURL request
13 $curl_params = array(
14 'address' => $listing_location,
15 'key' => $api_key
16 );
17
18 $api_url = sprintf('https://maps.googleapis.com/maps/api/geocode/json?%s', http_build_query($curl_params));
19
20 $ch = curl_init();
21 curl_setopt($ch, CURLOPT_URL, $api_url);
22 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
23 curl_setopt($ch, CURLOPT_REFERER, site_url());
24
25 if(defined('CURLOPT_IPRESOLVE') && defined('CURL_IPRESOLVE_V4')) {
26 curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
27 }
28
29 $json = curl_exec($ch);
30
31 if(!empty($json)) {
32 $data = json_decode($json);
33
34 // Parse the data
35 if(!empty($data->results)) {
36 $raw_address = $data->results[0];
37
38 // Extract the address parts
39 $long_names = $short_names = array();
40 if(!empty($raw_address->address_components)) {
41 foreach($raw_address->address_components as $component) {
42 if(empty($component->types)) {
43 continue;
44 }
45
46 foreach($component->types as $component_type ) {
47 $long_names[$component_type] = (!empty($component->long_name)) ? $component->long_name : "";
48 $short_names[$component_type] = (!empty($component->short_name)) ? $component->short_name : "";
49 }
50 }
51 }
52
53 // printf('<pre>%s</pre>', print_r($raw_address, true));
54
55 // Replace the tags
56 $default_uri = str_replace('%__city%', $long_names['locality'], $default_uri);
57 $default_uri = str_replace('%__state%', $long_names['administrative_area_level_1'], $default_uri);
58 $default_uri = str_replace('%__state2%', $long_names['administrative_area_level_2'], $default_uri);
59 $default_uri = str_replace('%__country%', $short_names['country'], $default_uri);
60 }
61 }
62 }
63
64 return $default_uri;
65}
66add_filter('permalink_manager_filter_default_post_uri', 'bis_listing_location_tag', 5, 5);
67
68function bis_googlemaps_api_fields($fields) {
69 $fields['third_parties']['fields']['googleapikey'] = array(
70 'type' => 'text',
71 'value' => '',
72 'input_class' => 'widefat',
73 'label' => __('Google Geocoding API key', 'permalink-manager'),
74 );
75
76 return $fields;
77}
78add_filter('permalink_manager_settings_fields', 'bis_googlemaps_api_fields', 9);