Responsive, Real-Time Graphs in WordPress: Plugins and Plotting

Justyn Hornor
This entry is part 4 of 6 in the series Build Responsive, Real-Time Graphs in WordPress

Build Responsive, Real-Time Graphs in WordPress

In this part of our series on creating a responsive, real-time graphs within a WordPress site, we’re going to finally get to the good stuff! The last three parts were for getting the newer designers up to speed. If you’re just arriving, skipped ahead too quickly, or got flagrantly confused, go back to the earlier parts and review a bit. Some of the code is fairly specific to this project, such as the Unix Timestamps needed to make our graph library work.

I’ve been building a simple pushups tracker form and database table for using with our Flot graphs. Of course, you can use just about any data source to populate the data in your pages. But, for the sake of teaching a newbie how to start working with forms and phpMyAdmin, I wanted to walk through the entire process from scratch.

Once you have this system in place within your WordPress site, you can literally create any kind of graphed data. The Flot graph library is extensive and very easy to implement. As I’ll be able to demonstrate, you can rinse and repeat with our pushups tracker and create a powerful system for displaying this data — all in real-time in a responsive website.

Step 1: Get the Flot Library

I’m using Flot for my graphs for lots of reasons, but mostly because it’s easy to implement and I was able to get it to work on every device imaginable. It uses the canvas feature in HTML5 to draw data and is capable of some crazy, amazing stuff. You can use whatever you want. But, for this tutorial we will be using Flot.

Specifically, we’re using my plugin (Flot for WordPress) to properly register and run the Flot library in WordPress. I highly recommend using the plugin, but you can implement Flot without it.

Flot for WordPress Plugin

Step 2: Make the Pushups Results Post

In WordPress, go to “Post”s > “Add New” and create a post with the title “Pushups Results.” In the body, put the following shortcode:

[pushups_results_sc]

Publish the post and you’re done. Right now, the post content will display the exact text “[pushups_results_sc]” because we haven’t actually created the function for the shortcode yet.

Step 3: Create Our Graph

In part 2 of this series, we created a new table in our WordPress database called pushups. We use it to store the pushups information from our forms. If you’re really comfortable with phpMyAdmin, go to the SQL tab and run this query to create the table we’ll be using:


CREATE TABLE `{Your Database}`.`pushups` (
`pushups_id` INT( 10 ) NOT NULL AUTO_INCREMENT ,
`pushups_count` INT( 3 ) NOT NULL ,
`pushups_date` VARCHAR( 15 ) NOT NULL ,
`pushups_wpuser` VARCHAR( 100 ) NOT NULL ,
`active` INT( 2 ) NOT NULL DEFAULT '1',
INDEX ( `pushups_id` )
) ENGINE = MYISAM

Everything up to this point has been about getting the infrastructure in place so that you can start pulling data and displaying it in awesome ways. From here on out, it’s all about the graphs!

Create a new PHP file and call it pushups_results.php. You’re going to upload this to your wp-content/plugins/flot-for-wp/flot folder after you’ve pasted the following code:


<?php
/*
Description: This code is meant to be called by a WordPress shortcode
It makes a call to the database and displays the data in a Flot chart.
Author: @jphornor and @tarahornor
License: GPL3
*/

// Here's our function!
function pushups_results(){

/*
Get the db connection. If you didn't create a connect_to_db.php
file, just add your own database connection info here
*/
include ("connect_to_db.php");
connect_to_db();
/*
This gets us the current logged in user and assigns the username
to the variable wpuser, which is used in the main query
*/
get_currentuserinfo();
$current_user = wp_get_current_user();
$wpuser = $current_user->user_login;

// The big test! If a user isn't logged in, they get NOTHING!
if(!is_user_logged_in())
{
echo '<a href="'. wp_login_url() . '">Login</a> to see pushup results!
<p><a href="' . home_url() . '/wp-register.php">Register</a> if you have not already.</p>';

}
else
{

// The query
$sql = mysql_query("select * from pushups where `pushups`.`pushups_wpuser` = '$wpuser' and `pushups`.`active`= 1 ORDER BY `pushups`.`pushups_date` ASC ");

/*
Min and Max queries. It's generally not necessary to have to produce
our own Min and Max figures for Flot, our process below creates a data
set that ends with a comma, which Flot interprets as a zero.
*/
$min = mysql_query("select pushups_count FROM pushups ORDER BY pushups_count ASC limit 1");
$max = mysql_query("select pushups_count FROM pushups ORDER BY pushups_count DESC limit 1");

// We need to calculate the min point on the graph
while ($row = mysql_fetch_array($min))
{
$min_count = $row['pushups_count'];
}
$min_count = $min_count * .9; // This gives us some breathing room on the chart

// Let's calculate the max point on the graph
while ($row = mysql_fetch_array($max))
{
$max_count = $row['pushups_count'];
}
$max_count = $max_count * 1.1; // This also gives us some breathing room on the chart

/*
Now we generate our JavaScript and HTML onto the page.
This isn't my favorite way to do it, but it gets the job done.
*/
echo ' <div id="flot-container">'; //Customize the width and height for your WP install in the layout.css file
echo ' <h1>Pushup Results for ' . $wpuser . '</h1>';
echo ' <script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/jquery.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/jquery.flot.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/jquery.flot.resize.js"></script>
<script language="javascript" type="text/javascript" src="' . plugins_url( $path ) . '/flot-for-wp/flot/excanvas.min.js"></script>
<link href="' . plugins_url( $path ) . '/flot-for-wp/flot/layout.css" rel="stylesheet" type="text/css">
<div id="placeholder" style="width:95%; height:85%; max-width:100%; margin:auto;"></div>
';
echo '
<script language="javascript" type="text/javascript" id="source">

jQuery(document).ready(function($){
var d1 = [
{ label: "Pushups Tracker for ' . $wpuser . '",
data: [';
while ($row = mysql_fetch_array($sql))
{
echo '[' .$row['pushups_date'] . ',' .$row['pushups_count'] . '],';
}
echo ' ]}];
var placeholder = $("#placeholder");
var plot = $.plot(placeholder, d1,
{
xaxis:
{ mode: "time" },
points:
{ show: true, symbol: "circle"},
lines:
{ show: true},
legend:
{ show: false },
yaxis:
{ min: ' .$min_count . ', max: ' .$max_count . ' }
} );
} );
</script></div>';
}
}
// The shortcode in the Pushups Result post
add_shortcode( 'pushups_results_sc', 'pushups_results' );
mysql_close();

?>

I know that’s a ton of information, and I did my best to add comments. Once again, this file called pushups_results.php goes in your wp-content/plugins/flot-for-wp/flot folder. I’m sorry for how compressed the code looks here, but if you download my resource files, you can see the contents in a much more organized format.

Recap

While this is a lot of code, take the time to review the comments. There’s a lot going on and if you don’t track with how Flot interprets data, you’re going to struggle using your own data.

In this piece, we tackled some pretty dense processes. I tried to make it easy on you by letting you copy and paste, but don’t get lazy! You cannot just add this plugin and get magically beautiful graphs. So take some time to review this code.

As a quick recap, in this part of the series we covered:

  • Grab the Flot plugin (for folks just jumping into the series)
  • Create a post to display results
  • Add the Flot code to the page that pulls our data and displays it properly.

Believe it or not, you’re actually mostly done! If you refresh your pushups results page, you should see a graph!

In the next part of this series, I will cover some very detailed discussions of how to work with PHP and MySQL with regards to Flot.

In the last part, I discuss how to style your graphs. So, if you’re a developer and got your graphs working right away, you may want to skip to later parts of this series.

Build Responsive, Real-Time Graphs in WordPress

<< Responsive, Real-Time Graphs in WordPress: Form ProcessingResponsive, Real-Time Graphs in WordPress: Dealing with Data >>

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.