In this mini-series of Google Visualization tutorials, we will be adding a Google chart to a WordPress theme without having to install any plugins but ensuring that we use the correct WordPress functions and recommended a safe way of implementing JavaScript. The data we will be pulling will be in JSON format and will be stored on the same server inside the theme directory. In this tutorial, we will be adding a stacked column chart. Want to add a table? Check out part 1
Access to your WordPress theme folder.
A little knowledge of PHP and WordPress functions is useful but not required.
In the Download above there is an example of a correctly formatted JSON file (Purely fictional of course) which we will use to populate our data to create our chart. Upload the js and data folder to your WordPress theme folder. If using a Child Theme upload to that folder rather than the parent.
Before we start to enable our ajax event to fire when non-admin users look at the page. Open up header.php and check to see if ajaxurl is defined. If not add the following just above the wp_head() function.
<?php if (!is_admin()){?>
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
<?php }?>
Naturally, you can’t have a chart without a container! In your blog post or page add the following
<div id="chart_div" class="chart"></div>
To add the JavaScript to our WordPress blog we need to officially enqueue our scripts so that they are present for the chart to load. Open up functions.php and add the following and save (Don’t close yet). Please note the comments at the top.
/*
*Enqueue Scripts for our chart
*
*Optional:
****1. Limit our table to display on a single page - https://codex.wordpress.org/Function_Reference/is_page
****2. If you are WORKING with a child theme replace all instances of get_template_directory_uri()
**** with get_stylesheet_directory_uri()
***/
function fundraising_chart(){
//if (is_page('page_name')){
wp_enqueue_script('chart', 'https://www.google.com/jsapi');
wp_enqueue_script('chart_main', get_template_directory_uri() . '/js/fundraising.min.js', array('jquery'));
//}
}
/*Add Javascript Action and our ajax actions that will be used in the fundraising chart script */ add_action( 'wp_enqueue_scripts', 'fundraising_chart' );
The Google Visualization library is quite heavy and unnecessary to load on each individual page or post. Simply uncomment Lines 13 & 16 to only load the JavaScript on a specific page, replacing page_name with the Page ID, Page Title or Page Slug. If you are displaying your chart in a blog post replace is_page() with is_single() See is_page() and is_single() on the WP Codex for further details.
With the JavaScript, files added we now need to add the following to functions.php which is the ajax action that is called from the JavaScript file. The build_graph function works a little differently to the build_table function in Part 1. After we have retrieved the JSON file we decode it and add all the values together for each category ie; school and our events. We then re-encode it to be parsed by JavaScript. This can also be done with JavaScript if required.
add_action( 'wp_ajax_build_graph', 'build_graph' );//admin
add_action('wp_ajax_nopriv_build_graph', 'build_graph');//frontend
function build_graph() {
$url = get_template_directory_uri() .'/data/donations.json';
$request = wp_remote_post($url);
// Get the body of the response
$response = wp_remote_retrieve_body( $request );
/*function get_sum will add all the amounts together and return the sum*/ function get_sum($json){
$keys = array();// Creates a new variable as an array
foreach( $json as $key){//loops through the sections
$sum[] = $key['amount'];//finds all amount values and adds them to an array
}
return array_sum($sum);//adds the all the values together
}
$myJson= json_decode($response, true);//decode file as an array
$company = get_sum($myJson['Company']);
$ct = get_sum($myJson['Collection Tins']);
$ourevents = get_sum($myJson['Our Events']);
$individual = get_sum($myJson['Individual']);
$misc = get_sum($myJson['Miscellaneous']);
$school = get_sum($myJson['School']);
/*echo json encoded array*/echo json_encode(
array( 'company'=>$company,
'ct'=>$ct,
'ourevents'=>$ourevents,
'individual'=>$individual,
'misc'=>$misc,
'school'=>$school));
die();//required for ajax
}?>
When your page or post loads the action build_graph is fired in functions.php. If successful it will load the contents of the JSON file and add them to the row (line 37)
var $j = jQuery;
// Load the Visualization API and the chart package.
google.load("visualization", "1", {packages:["corechart"]});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
/*Create our Chart through an Ajax request by passing the build_graph action which will be parsed with the build_gaph function in functions.php*/
function drawChart() {
$j.ajax({
url: ajaxurl,
data: {
"action": "build_graph" //run build_graph function in functions.php
},
dataType: "json",
success: function (data) {
/*data[''] represents the json data */ var company = data.company;
var ct = data.ct;
var ourevents = data.ourevents;
var individual = data.individual;
var misc = data.misc;
var school = data.school;
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Our Events');
data.addColumn('number', 'Individual');
data.addColumn('number', 'Company');
data.addColumn('number', 'School');
data.addColumn('number', 'Miscellaneous');
data.addColumn('number', 'Collection Tins');
data.addRow([null, ourevents, individual, company, school, misc, ct]);
// Set chart options
var options = {
//'width':600, //unhighlited width to allow for responsive graph - see CSS file in source
'height': 600,
'allowHtml': true,
'is3D': true,
hAxis: {
title: 'Types of Donations'
},
vAxis: {
format: 'u00A3'
},
'isStacked': true
};
var formatter = new google.visualization.NumberFormat({
prefix: "u00A3"
});
formatter.format(data, 1);
formatter.format(data, 2);
formatter.format(data, 3);
formatter.format(data, 4);
formatter.format(data, 5);
formatter.format(data, 6);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
});
}
/*The following will resize the chart in the browser*/$j(window).resize(function () {
drawChart();
});
Open up your theme’s stylesheet and add the following to make your chart responsive.
.chart {
width: 100%;
}
If you have followed all steps correctly you should now have a fully functioning Google Chart. If you have any problems with the code or don’t quite understand something please feel free to use the comment section below.
Welcome to Hot Web Dev October 2024, featuring the latest technology and web development news.… Read More
In this tutorial, you’ll build a fun and interactive guessing game using Svelte 5, the… Read More
Welcome to Hot Web Dev September 2024, featuring the latest technology and web development news.… Read More
The JavaScript guessing game tutorial is a simple beginner's project. It features modern JavaScript syntax… Read More
If you have been following the monthly Hot Web Dev magazine you will find the… Read More
Welcome to Hot Web Dev August 2024, featuring the latest technology and web development news.… Read More