Advertisement
geminilabs

glsr_create_carrier_term

Nov 7th, 2023
1,146
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.37 KB | None | 0 0
  1. <?php
  2.  
  3. function glsr_create_carrier_term(): array {
  4.     $dotNum = filter_input(INPUT_GET, 'dotNumber', FILTER_VALIDATE_INT);
  5.     if (empty($dotNum)) {
  6.         return []; // don't assign category if a dotNumber isn't requested
  7.     }
  8.     $termSlug = 'carrier_'.$dotNum;
  9.     if ($term = term_exists($termSlug, glsr()->taxonomy)) {
  10.         return $term;
  11.     }
  12.     $termName = glsr_get_carrier_name($dotNum);
  13.     if (empty($termName)) {
  14.         return glsr_create_fallack_carrier_term();
  15.     }
  16.     $term = wp_insert_term($termName, glsr()->taxonomy, ['slug' => $termSlug]);
  17.     if (is_wp_error($term)) {
  18.         glsr_log()->error($term->get_error_message());
  19.         return glsr_create_fallack_carrier_term();
  20.     }
  21.     return $term;
  22. }
  23.  
  24. function glsr_create_fallack_carrier_term(): array {
  25.     $termName = 'Unknown Carrier';
  26.     $termSlug = 'unknown_carrier';
  27.     if ($term = term_exists($termSlug, glsr()->taxonomy)) {
  28.         return $term;
  29.     }
  30.     return wp_insert_term($termName, glsr()->taxonomy, ['slug' => $termSlug]);
  31. }
  32.  
  33. function glsr_get_carrier_name(int $dotNum): string {
  34.     $apiUrl = 'https://mobile.fmcsa.dot.gov/qc/services/carriers/';
  35.     $apiKey = 'e9d6c0cb17ee98addddfc81f8af610f035949f50';
  36.     $url = sprintf('%s/%s/', untrailingslashit($apiUrl), $dotNum);
  37.     $url = add_query_arg('webKey', $apiKey, $url);
  38.     $response = wp_remote_get($url);
  39.     if (is_wp_error($response)) {
  40.         glsr_log()->error($response->get_error_message());
  41.         return '';
  42.     }
  43.     if ('200' != ($statusCode = wp_remote_retrieve_response_code($response))) {
  44.         glsr_log()->error(sprintf('Unable to connect to %s [%s]', $url, $statusCode));
  45.         return '';
  46.     }
  47.     $body = json_decode(wp_remote_retrieve_body($response), true);
  48.     return glsr_get($body, 'content.carrier.dbaName');
  49. }
  50.  
  51. function glsr_set_carrier_assigned_terms(array $args): array {
  52.     $term = glsr_create_carrier_term();
  53.     if (!empty($term['term_id'])) {
  54.         $args['assigned_terms'] = $term['term_id'];
  55.     }
  56.     return $args;
  57. }
  58.  
  59. add_action('site-reviews/defaults/site-review', 'glsr_set_carrier_assigned_terms');
  60. add_action('site-reviews/defaults/site-reviews', 'glsr_set_carrier_assigned_terms');
  61. add_action('site-reviews/defaults/site-reviews-form', 'glsr_set_carrier_assigned_terms');
  62. add_action('site-reviews/defaults/site-reviews-summary', 'glsr_set_carrier_assigned_terms');
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement