How to Use Google Charts in WordPress

Google’s original chart API was pretty easy to use in WordPress, but the new Visualization API is more of a challenge. Now you have to put JavaScript into the post/page header, and WordPress does not make that easy.

The approach you take will depend on how your website is structured. My approach may not work for you, however this post will still help you to think about the problem. You can see one of my charts in action on this page.

My approach has three components:

1) The PHP code that generates the data for a chart resides in a plugin which returns the JavaScript for the Google API.

2) The function in the plugin is called from the HEAD section of a new template that I use on posts/pages with charts.

3) The chart is then positioned in the body of the post/page with a DIV tag.

Since I only had a dozen or so pages with charts, I decided to use one template with code in the HEAD section that figures out which plugin function to call by looking at the page title:

if (get_the_title()==’Yearly Bar Chart’) {Call plugin function here.}

The real code is a large SWITCH statement. To see what the plugin produces, view the source code of the page that I linked to above, and scroll down to:

var data = google.visualization.arrayToDataTable

That’s the beginning of the plugin output.

The new API can make very nice charts, but it has a couple of large drawbacks that may annoy you. You can’t format the chart title very much. For example, you can’t center the text. You also cannot format your axis labels very much. For example, on some of my old charts, I had two rows of labels, and the new API cannot do that.