· 6 years ago · Oct 19, 2019, 02:04 AM
1<?php
2
3function memo_sendDataToAPI($setUnits, $origin, $destination, $apiKey) {
4
5 $args = [
6 'post_type' => 'distance_cache',
7 'meta_query' => [
8 [
9 'key' => 'dbf_from',
10 'value' => $origin,
11 'compare' => '=',
12 'type' => 'CHAR',
13 ],
14 [
15 'key' => 'dbf_to',
16 'value' => $destination,
17 'compare' => '=',
18 'type' => 'CHAR',
19 ],
20 [
21 'key' => 'dbf_units',
22 'value' => $setUnits,
23 'compare' => '=',
24 'type' => 'CHAR',
25 ],
26 ],
27 ];
28
29 // Try to fetch the cache post
30 $query = new WP_Query( $args );
31
32 // If cache contains the required key, return the stored response
33 if ($query->found_posts > 0) {
34 $hit = $query->posts[0];
35 file_put_contents(ABSPATH . "distance-based-fee.log", "CACHE HIT - $destination \n", FILE_APPEND | LOCK_EX);
36 return json_decode($hit->post_content, true);
37 }
38
39 file_put_contents(ABSPATH . "distance-based-fee.log", "CACHE MISS - $destination \n", FILE_APPEND | LOCK_EX);
40
41 // If request was not stored in cache, send the API request to Google
42 $response = sendDataToAPI($setUnits, $origin, $destination, $apiKey);
43
44 // Store the updated cache
45 $inserted = wp_insert_post([
46 'post_title' => $destination,
47 'post_content' => json_encode($response),
48 'post_type' => 'distance_cache',
49 'meta_input' => [
50 'dbf_from' => $origin,
51 'dbf_to' => $destination,
52 'dbf_units' => $setUnits,
53 ]
54 ]);
55
56 file_put_contents(ABSPATH . "distance-based-fee.log", "POST INSERTED: " . var_export($inserted, true) . " - $destination \n", FILE_APPEND | LOCK_EX);
57
58 return $response;
59}