EDIT: When I wrote this post no plugin existed to create and embed Google Charts within a WordPress blog. I’ve recently been made aware of the ChartBoot for WordPress plugin which seems to do exactly what I needed – although I haven’t looked at the plugin myself at the moment. It might be worth taking a look.

I needed to insert charts from Google’s Chart Tools into my other WordPress blog but found that it wasn’t straightforward. There were a few WordPress plugins that claimed to be able to do it but none seemed to do exactly what I needed so I came up with the approach below.

The finished product can be found in this open source versus closed source ESBs extract from my blog. I should first say by way of explanation that I’m not a proper programmer and am certainly not well versed with PHP so I’m sure others could improve on this approach. But it certainly does what I need.

I should also say that the approach I have taken relies on already having produced the JavaScript code that produces the chart. I simply needed a way to inject that code into the WordPress blog and to have it render the chart where I wanted it. So if you’re looking for an approach that automates the chart production you won’t find it here.

First a recap of how Google’s Chart Tools work.

  1. First you load Google’s JavaScript chart library. 
  2. You then specify a function to be called when the page loads. 
  3. This function needs to contain the code to create the chart, pass the data and tell Google to render it
  4. This function must also be passed a page element (usually a <div> tag) which controls where in your web page Google’s code will render the chart.

So to accomplish this I decided that I needed to do two things.

  • Firstly, I needed to modify my WordPress theme’s header.php code to ensure that I could load Google’s JavaScript routines and build a mechanism to insert the chart code. 
  • Secondly I had to create some additional fields on WordPress’ post entry page that allowed me to:
    • Specify whether the Google chart API should be loaded for this Post (#1 in the list above) – i.e. we don’t want to load the Google Chart Tools code unless this post actually has a chart to be rendered
    • Specify the code that should be called to render each chart (#3 on the list above)

Creating a Placeholder in the HTML

The first thing to do is to create placeholder(s) for the chart(s) in the HTML of the WordPress post. To do this switch to HTML view in the WordPress editor, locate the position where you want to insert the chart and add a <div> tag. Specify an ID that is unique to this chart. So for example, if I want to insert two charts into my post I would insert the following HTML.

This is some content that goes above the chart.
<div id="medchart1">This text is replaced by the chart but WordPress seems to need some text in the DIV or it removes it when you switch back to Visual mode.</div>
And this is some content that goes below the first chart and above the second chart
<div id="medchart2">This text is replaced by the chart</div>
And this is text that goes below the second chart.

Creating the Custom Fields

OK so that takes care of telling Google where to render the cart, now I need a way to allow me to create custom fields in WordPress that also allows me to access that field from the PHP code in WordPress’ header.php. For this I found the truly excellent Advance Custom Fields plugin. This plugin has two components – a UI that allows you to create the field groups and field codes and then the logic to substitute those fields using PHP when WordPress creates the page.

So I created a number of fields as shown below:

You can see the first field lgGV is the flag to say whether the Google Visualisation Chart Tools API should be loaded for this page. I’ve then shown three other fields named szGVDrawChartFunction1..3.These fields will contain the actual JavaScript code that, when executed will draw the chart.

Expanding the first field shows more detail.

Specifying Chart Details in the WordPress Post

So, now when I edit a WordPress post I can enter values into the fields above to reflect the chart settings I want for that particular post.

As shown below:

So for the post above, I’ve effectively created a number of PHP variables that will be available from WordPress’ PHP code. These are lgGV, szGVDrawChartFunction1,2 and 3. In my example above only szGVDrawChartFunction1 and 2 have values. The 3rd is left blank.

If you click on the image to enlarge it you will also see that I’ve modified the code that produces the charts to reference the <div> IDs we created above. The first code section references

...document.getElementById('medchart1')...

and the second code references

...document.getElementById('medchart2')...

This tells the Google Chart code to render the chart inside those <div> blocks that we created above.

Modifying header.php to access the advanced custom fields

The Advanced Custom Fields plugin provides a number of PHP functions that you can use to access these post variables from PHP. These include:

get_field()
the_field()
the_repeater_field()
get_sub_field()
the_sub_field()

Actually the the_repeater_field() function is only available in their paid plugin. I haven’t used that version but as you can see from the code below it would make my code much more streamline.

So, for example, to access my lgGV logical field within my WordPress theme’s header.php code,  I might write:

<?php if(get_field('lgGV')): ?>

The author of the plugin has done a great job at making it so simple to access field codes associated with specific posts from within the WordPress PHP subsystem.

Modifying the header.php code

So now I need to modify my theme’s header.php code to examine and use these post-level fields.

Here it is.

<?php if(get_field('lgGV')): ?>
	<script type="text/javascript" src="http://www.google.com/jsapi"></script>

	<script type="text/javascript" >
		google.load("visualization", "1", {packages:["table","corechart"]});
	</script>

	<script>

		google.setOnLoadCallback(function()
                {
                    drawChart1();

                    <?php if(trim(the_field('szGVDrawChartFunction2')!=='')): ?>
                    drawChart2();
                    <?php endif; ?>

                    <?php if(trim(the_field('szGVDrawChartFunction3')!=='')): ?>
                    drawChart3();
                    <?php endif; ?>

                });
		function drawChart1() {<?php strip_tags(the_field('szGVDrawChartFunction1')); ?>}
		function drawChart2() {<?php strip_tags(the_field('szGVDrawChartFunction2')); ?>}
		function drawChart3() {<?php strip_tags(the_field('szGVDrawChartFunction3')); ?>}

    </script>
<?php endif; ?>

I inserted this code immediately under the wp_head() function call in my existing header.php file. This ensures that this code block is run every time my blog creates and serves a page. I don’t know enough about WordPress internals or theme development to know if this is the correct place for every theme. But it works for me.

On to the code. I’m sure if you understand PHP better than I do it will be self explanatory but just in case.

Line 1 checks to see if the custom post field lgGV has been set to true and if it has it loads the Google libraries (lines 2-5). If not then the entire code block is skipped. For my blog I will only occasionally insert charts so I don’t want the overhead of making my vistors’ browser load libraries it isn’t going to need.

Lines 6 onwards is the declaration of the function that will be called once the page has finished loading.

Line 9 calls the first draw chart function drawChart1(). Here I assume that some code has been entered into the szGVDrawChartFunction1 custom field for this WordPress post.

Lines 10-12 check to see if anything was entered into the 2nd draw chart function and if it has,drawChart2() is called. This is repeated for the 3rd chart as well. Checking for the field being null stops me having to define and call empty functions.

Lines 17,18 and 19 define the drawChart1..3 functions. You can see that all I do is fill the function braces {} with the code that was entered into the relevant custom post fields in WordPress –  szGVDrawChartFunction1..3.

Important

A couple of important things to note here.

Firstly, the function definitions in lines 17-19 include the braces {}. So the code that is pasted inside them from the szGVDrawChartFunction1..3 custom post fields should be ONLY the code INSIDE the braces – not that actual braces themselves.

Secondly, the code that is pasted into these fields cannot currently contain new lines. I’m not sure why this is but I assume it is something to do with the way the PHP is rendered. So as a result I have to ensure that my chart definition code has all of the new lines removed. In effect each function appears on one line.

Things to Improve in Future Versions

I recognise that there is a lot of redundant code here and that it would be better using a loop to cycle through the various options but the Advanced Custom Field plugin doesn’t support repeating fields in the free version of the plugin. I did try to buy the commercial version but there seemed to be a problem with the author’s site at the time. I’ve just checked again and the store is now back online so I will get the commercial version and make my code tighter.

I also realise that inserting code into a template like this could be a security hole if someone could change the contents of my database, so I will have to build in some sort of protection too.

If you found this useful and understand PHP and/or WordPress I’d really welcome suggestions or improvements. Alternatively if you’ve found an existing plugin that can do the same I’d love to hear from you.

Dan.

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.