custom post types – Call external API based on user input


I want to create a WordPress website in which I want to display a search box on a page, where the user will be able to search for tracking numbers from different companies.
On searching a string in the search box, an external API call should be made based on that string and the data returned by the API should be shown to the user.
I’ve successfully fetched data from a test API, and the data is shown using custom post type with Advanced Custom Fields.

Right now a post is created for every single dataobject in the API, but what I want to achieve is, that if the searched string matches data (in this case a tracking number) from the API, a single post should be created based on that search.
So rather than creating thousands of posts from calling the API, I want to create a single post every time a search matches data from the API.

My code looks like this so far:

// Create custom post type for shipments
add_action('init', 'register_shipment_cpt');

function register_shipment_cpt() {
  register_post_type('shipment', [
    'label' => 'Shipments',
    'public' => true,
    'capability_type' => 'post'

/********* Connect to API and create posts from data *******/
// API url

$arguments = array(
    'method' => 'GET',

$response = wp_remote_get( $url, $arguments );

$results = json_decode( wp_remote_retrieve_body($response) );

foreach( $results as $result ) {
  $carrier_scac_code = $result->carrierScacCode;
  $voyage_number = $result->voyageNumber;
  $schedule_voyage_code = $result->scheduleVoyageCode;
  $service_code = $result->serviceCode;
  $service_name = $result->serviceName;
  $vessel_name = $result->vesselName;

  $single_shipment = array(
    'post_title' => $voyage_number,
    'post_type' => 'shipment',
    'post_status' => 'publish'

  $shipment_id = wp_insert_post($single_shipment);

  // Update ACF datafields
  update_field('carrierScacCode', $carrier_scac_code, $shipment_id );
  update_field('voyageNumber', $voyage_number, $shipment_id );
  update_field('scheduleVoyageCode', $schedule_voyage_code, $shipment_id );  update_field('serviceCode', $service_code, $shipment_id );
  update_field('serviceName', $service_name, $shipment_id );
  update_field('vesselName', $vessel_name, $shipment_id );

  if( is_wp_error( $single_shipment ) ) {

Buttered_Toast 1 year 2021-08-19T02:48:30-05:00 0 Answers 0 views 0

Leave an answer