Ask your WordPress questions! Pay money and get answers fast! (more info)

Pull In External API WordPress

Have a client who wants to pull in multiple external API's into multiple individual pages within their site. Need some assistance on how to do that.

Answers (2)

2015-12-29

Yosef VanTine answers:

Are you wanting to display it as a custom post type or just display results on a page. Do you know what apis you will be using?


Rocket1j comments:

Just display the results on the individual pages. If you can set-up one as an example we can likely figure out the rest. Below is a link to one of the API's to pull in.

https://api.myracepass.com/v2/schedules/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591


Rocket1j comments:

Great! That got all the data pulled in. It's just a garbled mess though. Any thoughts?
http://www.valleyspeedway.com/schedule/


Rocket1j comments:

Below is what the developer sent when showing where we are:

We will be using the API to build schedules that look like this:
http://www.allstarsprint.com/schedule/

Our logic is:
1. Make an API request for the schedule years (they are at the bottom) to build the paging links, this also gets us the most current year of schedules (/vs/schedules/years/)
2. Make a request for schedules (/v2/schedules/?key=xxx&scheduleyear=yyyy) with the current year as a query parameter. This gets a list of schedules for available for the current year. We allow sites to have multiple schedules to organize events how they need (speed weeks, etc)
3. Make a request for each schedule to get the events (/v2/schedules/events?key=xxx&scheduleId=SSS)
4. This is where you are now.
Parsing the JSON could be done many ways. We use .NET with a few libraries built into it for parsing. I assume PHP also has some parsing tools. I would also assume the main logic would be the same:
1. Loop through all objects in the "ScheduleEvents" array
2. Extract the EventName, EventDate, and EventDescription if needed.
3. Extract the track information from the Track object
4. Loop through the Class array and create a list of classes at the event (if desired)
5. Create a <tr></tr> for each event object in the "ScheduleEvents" array.
6. Append a column for the date
7. Append a column for the event information (track name, event name, classes)
8. Append a column for a link to the results (pass in the EventId to your results page so you can pull results)
9. Go to next event object in the "ScheduleEvents" array.
If "CancelType" is not empty, then the event has been cancelled. You can use this to display an icon or message on the site. I will have to get a list of possible "CancelType" values on the API documentation.

"ClassName" is the system set class name. Sites are allowed to override the class name and this value will be displayed in "ClassNameOverride". We display the ClassNameOverride, but fall back to ClassName if the override is blank.

"EventDescription" can get kinda long (1000 char max) so we generally do not show that in the schedule page. Just on a single event view.

Hopefully this helps a little. Depending on how familiar you are with JSON, there could be a bit of a learning curve. Unfortunately I know 0 PHP, so if your using that I won't be much help with actual code.

Let me know if I can help any further

2015-12-29

Rempty answers:

This code will get the data and show the results as a table

//URL request
$url="https://api.myracepass.com/v2/schedules/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591";
//Init curl
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

//convert data to array
$datos=json_decode($result,true);

echo '<table>';
echo '<thead>';
echo '<tr>';
echo '<th>ScheduleId</th>';
echo '<th>ScheduleName</th>';
echo '<th>ScheduleDesc</th>';
echo '<th>ScheduleYear</th>';
echo '<th>EventCount</th>';
echo '</tr>';
echo '</thead>';
foreach($datos['Schedules'] as $schedule){
echo '<tr>';
echo '<td>'.$schedule['ScheduleId'].'</td>';
echo '<td>'.$schedule['ScheduleName'].'</td>';
echo '<td>'.$schedule['ScheduleDesc'].'</td>';
echo '<td>'.$schedule['ScheduleYear'].'</td>';
echo '<td>'.$schedule['EventCount'].'</td>';
echo '</tr>';
}
echo '</table>';


Rocket1j comments:

K. Do we plug this code into the content filed in Wordpress or do we need to hard code in a PHP file? Or is there a plugin that we can work with and use shortcode?


Rempty comments:

Paste this code to functions.php

function schedule_shortcode($atts){
extract(shortcode_atts(array(
'url' => 'https://api.myracepass.com/v2/schedules/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591'
), $atts));

//curl init
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$datos=json_decode($result,true);
$ret= '<table>';
$ret.= '<thead>';
$ret.= '<tr>';
$ret.= '<th>ScheduleId</th>';
$ret.= '<th>ScheduleName</th>';
$ret.= '<th>ScheduleDesc</th>';
$ret.= '<th>ScheduleYear</th>';
$ret.= '<th>EventCount</th>';
$ret.= '</tr>';
$ret.= '</thead>';
foreach($datos['Schedules'] as $schedule){
$ret.= '<tr>';
$ret.= '<td>'.$schedule['ScheduleId'].'</td>';
$ret.= '<td>'.$schedule['ScheduleName'].'</td>';
$ret.= '<td>'.$schedule['ScheduleDesc'].'</td>';
$ret.= '<td>'.$schedule['ScheduleYear'].'</td>';
$ret.= '<td>'.$schedule['EventCount'].'</td>';
$ret.= '</tr>';
}
$ret.= '</table>';
return $ret;
}
add_shortcode('schedule_shortcode', 'schedule_shortcode');

Now you can add this shortcode in your pages, like this

[schedule_shortcode url="https://api.myracepass.com/v2/schedules/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591"/]


Rocket1j comments:

Great! And how would we handle a 2nd call to a different API url?


Rempty comments:

if the others url have the same json structure(results)
Just change the url in the shortcode

[schedule_shortcode url="my_custom_url"/]


Rocket1j comments:

So I had the wrong URL to pull in the individual event dates. Correct URL below:
https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627

However I'm not getting the full content at the below URL:
http://www.valleyspeedway.com/schedule/


This is in my functions.php:
function schedule_shortcode($atts){

extract(shortcode_atts(array(

'url' => 'https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627'

), $atts));



//curl init

$ch = curl_init();

// Disable SSL verification

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// Will return the response, if false it print the response

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Set the url

curl_setopt($ch, CURLOPT_URL,$url);

// Execute

$result=curl_exec($ch);

// Closing

curl_close($ch);



$datos=json_decode($result,true);

$ret= '<table>';

$ret.= '<thead>';

$ret.= '<tr>';

$ret.= '<th>ScheduleId</th>';

$ret.= '<th>ScheduleName</th>';

$ret.= '<th>ScheduleDesc</th>';

$ret.= '<th>ScheduleYear</th>';

$ret.= '<th>EventCount</th>';

$ret.= '</tr>';

$ret.= '</thead>';

foreach($datos['Schedules'] as $schedule){

$ret.= '<tr>';

$ret.= '<td>'.$schedule['ScheduleId'].'</td>';

$ret.= '<td>'.$schedule['ScheduleName'].'</td>';

$ret.= '<td>'.$schedule['ScheduleDesc'].'</td>';

$ret.= '<td>'.$schedule['ScheduleYear'].'</td>';

$ret.= '<td>'.$schedule['EventCount'].'</td>';

$ret.= '</tr>';

}

$ret.= '</table>';

return $ret;

}

add_shortcode('schedule_shortcode', 'schedule_shortcode');




This is the shortcode I'm using:

[schedule_shortcode url="https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627"/]


Rempty comments:

Use this

function schedule_shortcode($atts){
extract(shortcode_atts(array(
'url' => 'https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627'
), $atts));
$url=str_replace('&amp;','&',$url);
//curl init
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$datos=json_decode($result,true);
$ret= '<table>';
$ret.= '<thead>';
$ret.= '<tr>';
$ret.= '<th>EventId</th>';
$ret.= '<th>EventDate</th>';
$ret.= '<th>EventName</th>';
$ret.= '<th>EventDescription</th>';
$ret.= '<th>CancelType</th>';
$ret.= '<th>CancelMessage</th>';
$ret.= '<th>Track</th>';
$ret.= '<th>Classes</th>';
$ret.= '</tr>';
$ret.= '</thead>';
foreach($datos['ScheduleEvents'] as $schedule){
$ret.= '<tr>';
$ret.= '<td>'.$schedule['EventId'].'</td>';
$ret.= '<td>'.$schedule['EventDate'].'</td>';
$ret.= '<td>'.$schedule['EventName'].'</td>';
$ret.= '<td>'.$schedule['EventDescription'].'</td>';
$ret.= '<td>'.$schedule['CancelType'].'</td>';
$ret.= '<td>'.$schedule['CancelMessage'].'</td>';
$ret.= '<td>';
foreach($schedule['Track'] as $track){
$ret.='TrackID: '.$track['TrackId'].'<br/>';
$ret.='TrackName: '.$track['TrackName'].'<br/>';
$ret.='TrackCity: '.$track['TrackCity'].'<br/>';
$ret.='TrackState: '.$track['TrackState'].'<br/>';
$ret.='TrackCountry: '.$track['TrackCountry'].'<br/>';
}
$ret.='</td>';
$ret.= '<td>';
foreach($schedule['Classes'] as $track){
$ret.='ClassId: '.$track['ClassId'].'<br/>';
$ret.='ClassName: '.$track['ClassName'].'<br/>';
$ret.='ClassNameOverride: '.$track['ClassNameOverride'].'<br/>';
}
$ret.='</td>';
$ret.= '</tr>';
}
$ret.= '</table>';
return $ret;
}
add_shortcode('schedule_shortcode', 'schedule_shortcode');


Rempty comments:

How you want to show the data?


Rocket1j comments:

It should be displaying similar to this link:
http://www.allstarsprint.com/schedule/


Rempty comments:

Hello Rocket1j
plz test this new function, i deleted the useless fields(blank fields), and changed the position like http://www.allstarsprint.com/schedule/ , but i didn't apply any style.


function schedule_shortcode($atts){
extract(shortcode_atts(array(
'url' => 'https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627'
), $atts));
$url=str_replace('&amp;','&',$url);
//curl init
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$datos=json_decode($result,true);
$ret= '<table width="100%">';
$ret.= '<thead>';
$ret.= '<tr>';
$ret.= '<th>Date</th>';
$ret.= '<th>Track</th>';
$ret.= '<th>Canceled</th>';
$ret.= '</tr>';
$ret.= '</thead>';
foreach($datos['ScheduleEvents'] as $schedule){
$ret.= '<tr>';
$ret.= '<td valign="top">'.$schedule['EventDate'].'</td>';
$ret.= '<td>';
foreach($schedule['Track'] as $track){
//$ret.='TrackID: '.$track['TrackId'].'<br/>';
$ret.=$track['TrackName'].' - ';
$ret.=$track['TrackCity'].', ';
$ret.=$track['TrackState'].'<br/>';
//$ret.='TrackCountry: '.$track['TrackCountry'].'<br/>';
$ret.='<div class="classes-track">';
foreach($schedule['Classes'] as $track2){
// $ret.='ClassId: '.$track['ClassId'].'<br/>';
if($track2['ClassNameOverride']!=''){
$ret.=$track2['ClassNameOverride'].'<br/>';
}else{
$ret.=$track2['ClassName'].'<br/>';
}
}
$ret.='</div>';
}
$ret.='</td>';
if($schedule['CancelType']!=''){
$ret.= '<td>'.$schedule['CancelType'].'</td>';
}else{
$ret.='<td>No</td>';
}
$ret.= '</tr>';
}
$ret.= '</table>';
return $ret;
}
add_shortcode('schedule_shortcode', 'schedule_shortcode');


Rocket1j comments:

Nice work! We're making good progress.

How can we remove the Canceled column and add in the dynamic Details column that takes the user to the individual event page similar to the All-Stars site? And add some spacing between events

Thanks!


Rempty comments:

Ok, there is some considerations

All the events are not been saved to your wordpress db, and i am queryng from the API url.
You must create a page called "Event Details", i need this to show the event details(send me the url).
From the API just i can show (example of url to call event details https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&EventID=104703):

Title: Date + Track name
Location: City, State

Event Classes: List of all Class Names

All this will be packed on a shortcode.
Is this ok?


Rocket1j comments:

The Date, Event Name, and Event Classes would be all that is needed to be displayed on the schedule page.

The details page could incorporate all the above and any event details provided.

http://www.valleyspeedway.com/schedule/event-details/

Thanks again for the work here.


Rempty comments:

OK, replace my old function with

function schedule_shortcode($atts){
extract(shortcode_atts(array(
'url' => 'https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627'
), $atts));
$url=str_replace('&amp;','&',$url);
//curl init
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

$datos=json_decode($result,true);
$ret= '<table width="100%">';
$ret.= '<thead>';
$ret.= '<tr>';
$ret.= '<th width="100px">Date</th>';
$ret.= '<th>Track</th>';
$ret.= '<th></th>';
$ret.= '</tr>';
$ret.= '</thead>';
foreach($datos['ScheduleEvents'] as $schedule){
$ret.= '<tr>';
$ret.= '<td style="padding-bottom:20px;" valign="top">'.$schedule['EventDate'].'</td>';

$ret.= '<td style="padding-bottom:20px;">';
foreach($schedule['Track'] as $track){
$ret.=$track['TrackName'].' - ';
$ret.=$track['TrackCity'].', ';
$ret.=$track['TrackState'].'<br/>';
$ret.='<div class="classes-track">';
foreach($schedule['Classes'] as $track2){
if($track2['ClassNameOverride']!=''){
$ret.=$track2['ClassNameOverride'].'<br/>';
}else{
$ret.=$track2['ClassName'].'<br/>';
}
}
$ret.='</div>';
}
$ret.='</td>';
$ret.='<td>';
$ret.='<a href="'.get_permalink('1149').'?EventID='.$schedule['EventId'].'">Details</a>';
$ret.='</td>';
$ret.= '</tr>';
}
$ret.= '</table>';
return $ret;
}
add_shortcode('schedule_shortcode', 'schedule_shortcode');


And add this new to your functions.php:

function event_shortcode($atts){
extract(shortcode_atts(array(
'url' => 'https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591',
'EventID'=>'0'
), $atts));
if(isset($_GET['EventID']) && $_GET['EventID']!=''){
$eventid=$_GET['EventID'];
}
$url2=$url.'&EventID='.$eventid;
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url2);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);
$datos=json_decode($result,true);
$ret2="";
if($eventid!=''){
foreach($datos['ScheduleEvents'] as $schedule){
foreach($schedule['Track'] as $track){
//$ret.='TrackID: '.$track['TrackId'].'<br/>';
$trackname=$track['TrackName'];
$trackcity=$track['TrackCity'];
$trackstate=$track['TrackState'];
foreach($schedule['Classes'] as $track2){
// $ret.='ClassId: '.$track['ClassId'].'<br/>';
if($track2['ClassNameOverride']!=''){
$classnames[]=$track2['ClassNameOverride'].'<br/>';
}else{
$classnames[]=$track2['ClassName'].'<br/>';
}
}
}
$ret2='<h2>'.$schedule['EventDate'].' at '.$trackname.'</h2>';
$ret2.='<h3>Event Information</h3>';
$ret2.=$trackcity.', '.$trackstate;
$ret2.='<br/><br/>Event Classes<br/>';
foreach($classnames as $classes){
$ret2.=$classes.'<br/>';
}
}
}
return $ret2;
}
add_shortcode('event_shortcode', 'event_shortcode');


In your Event Details page add the shortcode
[event_shortcode/]


Rocket1j comments:

When I posted the "New" code in and tried to access the site I would get the below error:

Parse error: syntax error, unexpected end of file in /home/valleysp/public_html/wp-content/themes/porto/functions.php on line 398


Rempty comments:

Please check if you copied and pasted all code, because the code doesn't have any error.


Rocket1j comments:

Bingo! You're right that was on my end.

So for us to build in Point Standings on a different page using the below example call ... how would we do that?
https://api.myracepass.com/v2/points/classes/?key={xxx}&ScheduleId={id}


Rempty comments:

You need to know the structure of the json response.
If is different (different field names and structure), you need to create other function to parse this new json.

If not, you can use the parameter url from my shortcode
[schedule_shortcode url='https://api.myracepass.com/v2/schedules/events/?key=db4eccfe-7a13-48ad-9ccc-23d19c4dd591&ScheduleId=4627'/]


Rocket1j comments:

It's likely different. Let me look into that and get back at you.


Rocket1j comments:

What would it take to create a plugin to handle these various calls going forward? Instead of having to hardcode them in.


Rempty comments:

Each call to API have diferent results and fields (Schedules, points, etc).
And you want to show in the page the diferent results.

The problem is the JSON, have diferent structure for each url.

Yes, is posible create a plugin, but the results will be hardcode for each API call (same as using functions.php)


Rocket1j comments:

Hmm. Do you see a good way for us to handle all of this going forward keeping in mind that this will need to be replicated for dozens of sites possibly many, many more.


Rempty comments:

Is it only there are schedules and points?

If yes.

Example for Schedules

Convert to plugin, add configuration to put the API KEY, on install create the Schedule page and the Event Page.
Default Schedule API CALL = https://api.myracepass.com/v2/schedules/events/?key={your-api-key}&ScheduleId=4627
You can overwrite it modifying the parameter url in the shortcode created in the Schedule Page.

The Layout will be the same as http://www.valleyspeedway.com/schedule/

All this will take some time and more budget


Rocket1j comments:

Give me an idea on time and budget and we'll go from there.


Rempty comments:

i sent you a private message