Skip to content

Instantly share code, notes, and snippets.

@epierpont
Last active October 21, 2020 11:19
Show Gist options
  • Save epierpont/b6e6d2701e1d6f140ca474174eb8ccf6 to your computer and use it in GitHub Desktop.
Save epierpont/b6e6d2701e1d6f140ca474174eb8ccf6 to your computer and use it in GitHub Desktop.
WP Get Covid-19 Data
<?php
/**
* Get covid data and return as array.
*/
public function get_covid_data() {
$content = [];
$pub_array = $this->pub_counties[$this->pub_name];
if ( false === ( $covid_content = get_transient( 'swift_module_covid_' . $this->pub_name ) ) || empty( get_option( '_transient_timeout_swift_module_covid_' . $this->pub_name ) ) ) {
date_default_timezone_set( get_option( 'timezone_string' ) );
$today = date( 'Y-m-d' );
$yesterday = date( 'Y-m-d', strtotime( '-1 day', strtotime( $today ) ) );
foreach ( $pub_array as $state => $counties ) {
$county_keys = $county_array = [];
// Try to get feed for today.
$covid_feed_array = $this->get_covid_feed( $today, $state );
// If we have an empty feed for today, grab yesterday.
if ( empty( $covid_feed_array['data'] ) ) {
$covid_feed_array = $this->get_covid_feed( $yesterday, $state );
}
// Get all of the feed counties.
$feed_counties = !empty( $covid_feed_array['data'][0]['region']['cities'] ) ? $covid_feed_array['data'][0]['region']['cities'] : '';
// If we actually have counties to work with.
if ( !empty( $feed_counties ) ) {
// Loop through each $county and search within $feed_counties for a match, return correct key.
foreach( $counties as $county ) {
$county_keys[]= array_search( $county, array_column( $feed_counties, 'name' ) );
}
}
// If we don't have any data, return false.
else {
return;
}
// Assemble final array, starting with state data.
$covid_data = $covid_feed_array['data'][0];
unset($covid_data['region']);
$covid_data['state'] = $state;
// If we have matching keys.
if ( !empty( $county_keys ) ) {
// Loop through and build county data.
foreach ( $county_keys as $county_key ) {
$county_array[] = $feed_counties[$county_key];
}
}
// Add county data to final array.
$covid_data['counties'] = $county_array;
$content[] = $covid_data;
}
$covid_content = json_encode( $content );
set_transient( 'swift_module_covid_' . $this->pub_name, $covid_content, 60 * MINUTE_IN_SECONDS );
}
return $covid_content;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment