Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
/**
* Load an external CSV file and store it as a transient
*/
function get_the_csv_data() {
$transient_key = 'the-csv-data';
$data = get_transient( $transient_key );
// If the data already exists then return it. We're done here!
if ( false !== $data ) {
return $data;
}
// Fetch the CSV data
$request = wp_remote_get( 'https://s3.amazonaws.com/bsp-ocsit-prod-east-appdata/datagov/wordpress/2019/09/opendatasites91819.csv' );
// Retrieve the body contents from the request
$raw_csv_string = wp_remote_retrieve_body( $request );
// Convert the CSV string to an array of CSV data
$csv = str_getcsv( $raw_csv_string );
// Process your CSV data somewhow
$data = '';
// Store the result for 15 minutes
set_transient( $transient_key, $data, 15 * MINUTE_IN_SECONDS );
return $data;
}
/**
* Register the Google Charts loader script
*/
function action_init() {
wp_register_script(
'google-charts-library',
'https://www.gstatic.com/charts/loader.js',
$deps = array(),
$ver = null,
$in_footer = false
);
}
add_action( 'init', 'action_init' );
/**
* Output the data to a Google Visualization Gauge Chart
*
* @link https://developers.google.com/chart/interactive/docs/gallery/gauge
*/
function action_wp_enqueue_scripts() {
$csv_data = get_the_csv_data();
ob_start();
?>
google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Thing 1', <?php echo absint( $csv_data[2] ); ?>],
['Thing 2', <?php echo absint( $csv_data[4] ); ?>],
]);
var options = {
width: 400, height: 120,
redFrom: 90, redTo: 100,
yellowFrom:75, yellowTo: 90,
minorTicks: 5
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
chart.draw(data, options);
}
<?php
$the_javascript_goodness = ob_get_clean();
wp_add_inline_script( 'google-charts-library', $the_javascript_goodness, $position = 'after' );
}
add_action( 'wp_enqueue_scripts', 'action_wp_enqueue_scripts' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment