Skip to main content Jump to list of all articles

Adding Google Charts to WordPress Blog Part 2

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

Image of Stacked Column Chart
Image provided by Shutterstock

Prerequisites

Access to your WordPress theme folder.
A little knowledge of PHP and WordPress functions is useful but not required.

Download

Let’s get started

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.

Ajax in the head

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 }?>

Add the Chart container to the Blog Post/Page

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>

Enqueue Our scripts

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.

Build Table Action

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
	
}?>

Fundraising.js

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();
});

Add a little CSS Spice

Open up your theme’s stylesheet and add the following to make your chart responsive.

.chart {
	width: 100%;
}

 Conclusion

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.

Example of Google Charts

 Further Reading

18 replies on “Adding Google Charts to WordPress Blog Part 2”

Gary Sanders
Gary Sanders On

Thanks for this easy to follow tutorial! I was able (after removing the stray space that Ian pointed out) to get a page from my site to call your chart. I have a working chart that I can display in HTML, but I haven’t been able to figure out how to modify it to call it successfully from WordPress. Would you be willing to take a look at it and point me in the right direction? Thanks!

You’ve got a space in this that stops it from working.

 
wp_enqueue_script('chart_main', get_template_directory_uri() . ' /js/fundraising.min.js', array('jquery'));

But otherwise this was great.

I already had other scripts set up and I used wp_localize_script to set my ajaxurl. This might be a proplem for some using your code. If they set the ajaxurl in the head would it not reset the others set in the functions.php?

Many thanks for taking the time to write and post this.

Gary Sanders
Gary Sanders On

Thanks for that catch, Ian! That’s exactly what was keeping mine from working. Now to see if I can edit the code to make it work for my chart…

Moritz Leiser
Moritz Leiser On

Hey, thanks for this 2 awesome posts. I am trying to do the same, but with a MAP!. You don’t happen to have planned a post about including the map chart in wordpress? Am trying to see trough and will eventually succeed, but if someone already has all the code figured out it would be easier 😉
Regards
Moritz

Hi Moritz. I have successfully got it working. Sorry it took a while but I’ve been super busy. Hopefully I will publish the tutorial this week but if you are wanting to test the code out, email me and I’ll package the code up for you. 🙂

Hi,
This is exactly what I’ve been looking for… I can’t seem to find the tutorial you were talking about though. Did you manage to post it yet? If not, could you share the code with me?

Comments are closed.

Discover more from WorldOWeb

Subscribe now to keep reading and get access to the full archive.

Continue reading