Skip to content

Instantly share code, notes, and snippets.

@igorbenic
Created November 23, 2022 22:17
Show Gist options
  • Save igorbenic/2f9f0909599e31f3f597427199c8e583 to your computer and use it in GitHub Desktop.
Save igorbenic/2f9f0909599e31f3f597427199c8e583 to your computer and use it in GitHub Desktop.
A simple shortcode to display results from World Cup 2022 using api-football.com APIs
<?php
/**
* Plugin Name: Live API
*/
add_action( 'init', function(){
add_shortcode( 'live_api', 'live_api_shortcode' );
});
function live_api_shortcode() {
$leagues = live_api_run( 'leagues/?id=1' );
$fixtures = live_api_run( 'fixtures/?league=1&season=2022' );
ob_start();
echo '<img class="live-logo" src="' . $leagues['response'][0]['league']['logo'] . '"/>';
echo '<h2 class="live-heading">Results</h2>';
?>
<style>
.live-logo {margin: 0 auto; display: block;}
.live-heading {font-size: 1.5em;text-align: center}
.fixture {
padding: 1em;
border-radius: 5px;
border: 1px solid rgba(0,0,0,0.1);
}
.fixture-header,
.fixture-teams {
display: flex;
justify-content: space-between;
}
.fixture-teams {
margin-top: 1em;
align-items: center;
}
.fixture-team {
order: 1;
}
.fixture-team:nth-child(2) {
order: 3;
text-align: right;
}
.fixture-goals {
order: 2;
align-self: center;
font-size: 2em;
}
.fixture-goals small {
font-size: 0.5em;
display: block;
text-align: center;
}
.fixture-team img {
display: block;
width: 100px;
}
.fixture-status {
text-align: right;
}
.fixture-venue,
.fixture-status {
font-size: 0.875em;
}
.fixture-venue small {
display: block;
}
</style>
<?php
foreach ( $fixtures['response'] as $fixture ) {
?>
<div class="fixture">
<div class="fixture-header">
<div class="fixture-venue">
<?php echo $fixture['fixture']['venue']['name']; ?>
<small><?php echo $fixture['fixture']['venue']['city']; ?></small>
</div>
<div class="fixture-status">
<div class="date"><?php echo date( 'Y-m-d', $fixture['fixture']['timestamp'] ); ?></div>
<small class="hour"><?php echo date( 'H:i', $fixture['fixture']['timestamp'] ); ?></small>
</div>
</div>
<div class="fixture-teams">
<?php
foreach ($fixture['teams'] as $type => $data) {
echo '<div class="fixture-team">';
echo '<img src="' . $data['logo'] . '"/>';
echo '<span>' . $data['name'] . '</span>';
echo '</div>';
}
?>
<div class="fixture-goals">
<?php
echo $fixture['goals']['home'] . '-'. $fixture['goals']['away'] ;
?>
<?php if ( $fixture['fixture']['status']['elapsed'] ) : ?>
<small><?php echo $fixture['fixture']['status']['elapsed']; ?>'</small>
<?php endif; ?>
</div>
</div>
</div>
<?php
}
return ob_get_clean();
}
function live_api_run( $api ) {
$url = 'https://v3.football.api-sports.io/';
$api_key = 'API_KEY';
$response = wp_remote_get(
$url . $api,
[
'headers' => [
'x-rapidapi-host' => $url,
'x-rapidapi-key' => $api_key
]
]
);
return json_decode( wp_remote_retrieve_body( $response ), true );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment