skip to main content

Adding Google Charts to WordPress Blog Part 1

0

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 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 table. Want to add a chart?  Checkout part 2

JSON - Creating a Google 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

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 table. 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.

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

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 table to load.  Open up functions.php and add the following and save (Don’t close yet).   Please note the comments at the top.

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.

Fundraising.js

When your page or post loads the action build_table is fired in functions.php. If successful it will load the contents of the JSON file and add them to the row (line 28)

Add a little CSS spice

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

 Conclusion

If you have followed all steps correctly you should now have a fully functioning Google Chart table.  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 Chart Table

 Further Reading