Advertisement
geminilabs

Untitled

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