Displaying WordPress Site Data Via jQuery Charts

Displaying WordPress Site Data Via jQuery Charts

Tutorial Details
  • Program: WordPress
  • Version: 3.0 and higher
  • Difficulty: Beginner - Intermediate
  • Estimated Completion Time: 20-30 minutes
This entry is part 1 of 6 in the series WordPress Dashboard Customizations

In this tutorial we will use the jQuery Charts Plotting plugin, JQplot, to create a new WordPress plugin which can display some of your blog’s traffic, popular categories, and more with some beautiful visual charts. Looking for a way to pimp out a client’s dashboard (or your own!) with some useful infographics? Look no further… we’ll show you how it’s done right here.


Step 1 Creating Theme:

As a jQuery chart library we choose JQplot which is easy to use and open-source under GPL, MIT licenses. We will give 4 different charts in this post, but then by using our fantasy you can make more charts related to your WordPress site data. We will call our plugin Infograph. You can download and install ready plugin from download link given in this post. Now let’s look structure of plugin step by step: The plugin contains 6 functions (1 for JS script enque, one for CSS, and 4 ones for charts), 4 shortcodes for charts and 2 action hooks. I hope you all know what is shortcode and action, so let’s go on.

First we add 2 functions for adding JS and CSS support:

function myscripts ()
{
wp_deregister_script('jquery'); 
wp_register_script( 'jquery',get_bloginfo('wpurl') . "/wp-content/plugins/infograph/jquery-1.3.2.min.js");
wp_enqueue_script('jquery'); 
 
wp_register_script( 'jqplot',get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/jquery.jqplot.js");
wp_enqueue_script( 'jqplot' );

wp_register_script( 'bar', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.barRenderer.js");
wp_enqueue_script( 'bar' );

wp_register_script( 'cax', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.categoryAxisRenderer.js");
wp_enqueue_script( 'cax' );

wp_register_script( 'pol', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.pointLabels.js");
wp_enqueue_script( 'pol' );
 
wp_register_script( 'fun', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.funnelRenderer.js");
wp_enqueue_script( 'fun' );

wp_register_script( 'pie', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.pieRenderer.js");
wp_enqueue_script( 'pie' );

wp_register_script( 'meg', get_bloginfo('wpurl') . "/wp-content/plugins/infograph/src/plugins/jqplot.meterGaugeRenderer.js");
wp_enqueue_script( 'meg' );

}

function add_css () {
	 echo '
	 <link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/infograph/src/jquery.jqplot.css" />' ;
	 echo '<link type="text/css" rel="stylesheet" href="' . get_bloginfo('wpurl') . '/wp-content/plugins/infograph/examples.css" />' ;
} 

add_action('wp_enqueue_scripts', 'myscripts');
add_action('wp_head', 'add_css'); 

Step 2 “Popular Categories” Chart:

This chart is a pie which shows the most popular categories of your blog. You can place it to any page or post. Just put [ mycategories ] shortcode to any post:

function categories($atts,$content = '') {
$ch_cats = get_categories(array('orderby'=>'count','order'=>'desc') );
$sayy= count($ch_cats);
$chl='';
for ($i=1;$i<=5;$i++)
  {
    $chl=$chl.'[\''.$ch_cats[$i-1]->name.'\','.$ch_cats[$i-1]->count.'],';  //[[[\'a\',25],[\'b\',14],[\'c\',7]]]
     }

$chl='[['.substr($chl,0,-1).']]';  

return '<script>
$(document).ready(function(){
plot1 = $.jqplot(\'chart1\', '.$chl.', {
title: \'Most popular categories of example.com\',
seriesDefaults:{renderer:$.jqplot.PieRenderer,rendererOptions: { padding: 8, showDataLabels: true}},legend:{show:true,placement: \'outside\',rendererOptions: {numberRows: 1}},
legend:{show:true, 
        placement: \'outside\', 
        rendererOptions: {
        numberRows: 1
                     }, 
        location:\'s\',
        marginTop: \'15px\'
                  }       
  });
});
  </script>
  <div id="chart1" style="margin-top:30px;margin-bottom:30px; margin-left:20px; width:500px; height:300px;"></div>  ';
 }
add_shortcode('mycategories', 'categories');

Step 3 “Activity By Month” Chart:

This chart can display last 12 months activity in your blog. It shows how many posts you have posted last 12 monthes by month.

function postsbymonth($atts,$content = '') {
	// Post count by month
global $wpdb,$wp_query;
$postcountbymonth=$wpdb->get_results("select * from (select  MONTH(post_date) as mo,YEAR(post_date) as ye,count(ID) as co from $wpdb->posts 
where post_status='publish'
group by MONTH(post_date),YEAR(post_date) order by post_date desc limit 12) a order by ye asc,mo asc");
$labels='';$postcounts='';
foreach ($postcountbymonth as $pc) 
 {
	 $labels=$labels.'\' '.$pc->mo.'/'.$pc->ye.' \',';
	 $postcounts=$postcounts.$pc->co.',';
 }
$postcounts='['.substr($postcounts,0,-1).']';
$labels='['.substr($labels,0,-1).']';
  
return '
<script language="javascript" type="text/javascript">
$(document).ready(function(){
        $.jqplot.config.enablePlugins = true;
        var s1 = '.$postcounts.';
        var ticks = '.$labels.';
        plot1 = $.jqplot(\'chart2\', [s1], {
            seriesDefaults:{
                renderer:$.jqplot.BarRenderer,
                pointLabels: { show: true }
            },
            axes: {
                xaxis: {
                    renderer: $.jqplot.CategoryAxisRenderer,
                    ticks: ticks
                }
            },
            highlighter: { show: false }
        });
    });
</script>
  <div id="chart2" style="margin-top:20px;margin-bottom:20px; margin-left:20px; width:500px; height:250px;"></div>
  ';
 }
add_shortcode('bymonth', 'postsbymonth');

Step 4 “The Most Commented Posts” Chart:

Third chart is also about interesting data, it shows your the most commented posts.

function mostcommented($atts,$content = '') {
global $wpdb,$wp_query;
$postcountbymonth=$wpdb->get_results("select post_title as pt,comment_count as co from $wpdb->posts where post_status='publish' order by co desc limit 5");
$labels='';$titles='';
foreach ($postcountbymonth as $pc) 
 {
	 $titles=$titles.'[\' '.$pc->pt.' ('.$pc->pt.') \','.$pc->co.'],';
	 
 }

$titles='['.substr($titles,0,-1).']';
  return '
  <style>.jqplot-table-legend{width:200px}
  #chart4 table tr td:nth-child(odd){width:20px;}
  </style>
<script  type="text/javascript">
$(document).ready(function(){
    s1 = '.$titles.';
    plot4 = $.jqplot(\'chart4\', [s1], {
        seriesDefaults:{
            renderer:$.jqplot.FunnelRenderer,
            rendererOptions: {
                showDataLabels: false
               
            }
        },
        legend: {
            show: true,
            placement: \'outside\'
        }
    });
});
</script>
  <div id="chart4" style="margin-top:20px;margin-bottom:20px; margin-left:20px; width:350px; height:300px;"></div>
  ';
 }
add_shortcode('mypopularposts', 'mostcommented');

Step 5 “Blog Velocity” Chart:

Our last chart for this tutorial shows velocity of your blog. It shows average number of your post count by month.

function velocity($atts,$content = '') {

global $wpdb,$wp_query;

$postcountbymonth=$wpdb->get_results("select post_title as pt,comment_count as co from $wpdb->posts where post_status='publish'");
$postcountresult= round($wpdb->num_rows/12);

$maxvel=pow(10,strlen((string)$postcountresult));
$ticks='';	
$intervals='';	

for ($i=1;$i<=6;$i++){
	$ticks=$ticks.($maxvel*($i-1)/5).',';
	if($i % 2 != 0)
	  {
		  $intervals=$intervals.($maxvel*($i-1)/5).',';
		  }
	}

$ticks='['.substr($ticks,0,-1).']';	
$intervals='['.substr($intervals,0,-1).']';	

  return '
  <script>
  $(document).ready(function(){
   s1 = ['.$postcountresult.'];
   plot5 = $.jqplot(\'chart5\',[s1],{
       title: \'Your blog post velocity by month\',
       series: [{
           renderer: $.jqplot.MeterGaugeRenderer,
           rendererOptions: {
               label: \'Blog velocity\',
               labelPosition: \'bottom\',
               ticks: '.$ticks.',
               intervals:'.$intervals.',
           }
       }],
   });
});
</script>
<div id="chart5" style="margin-top:20px;margin-bottom:20px; margin-left:20px; width:350px; height:300px;"></div>';
 }
add_shortcode('velocity', 'velocity'); 

Using WordPress API’s and jQuery charts you can prolongate this chart list, these 4 charts was just examples for interested developers.

That’s all. Good luck.


Other parts in this series:12 Useful Customization and Branding Tweaks for the WordPress Dashboard
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Alex

    Thanks!

  • http://whysodumb.com Abhimanyu

    Nice and easy. But I do not use wordpress comments system on my website and am content with facebook comments.

    So, how do I arrange posts based on the number of facebook comments and likes? I use a normal code attached to the single.php instead of the wordpress plugin which goes by the same name.

    It’d be great if you could enlighten me on how can I track facebook comments on the site.

    Everything else worked like a charm. Thanks.

  • http://mobiland.az AzeriFire

    Thank you very much! Easy to use.

  • http://webania.net Elvin
    Author

    Thanks for comments.
    Abhimanyu, why aren’t you using WordPress native comments system or Disquss system whish is integrated with native system? IMHO it is not good to use third party comment system, because Facebook can even tomorrow close this API, what will you do if FB closes comments API? Nothing. So i don’t advice to use 3rd party comment system.
    You can edit this plugin and get needed result, but for it you must have practise about Facebook API’s. Here is en example how to get comment count from Facebook.
    http://stackoverflow.com/questions/4001548/retrieving-comment-count-from-fbcomments-widget-facebook
    When you get it, then you can integrate this data with this plugin

    • http://whysodumb.com Abhimanyu

      Yes, so true. But disqus requires a sign up, right.

      What do you suggest I do? My user-base is college students and I want hassle free commenting. I would like a picture to go with the comment and few college students know what is gravatar..

      http://whysodumb.com

      Thanks.

  • http://www.damiencarbery.com Damien

    Why is the Infograph plugin using an old version of JQuery instead of that included with WordPress?

    • http://webania.net Elvin
      Author

      Damien, thanks for note. Yeah it hasn’t any special reason, you can replace that line with the Jquery file of WordPress core. The plugin doesn’t need additional Jquery file in it.

      • http://www.damiencarbery.com Damien

        Good to hear that those lines are not required.
        May I suggest that you set dependencies in the wp_register_script() calls. You wouldn’t have to explicitly include jquery or jqplot scripts as they would be included as dependencies of the other scripts.
        Also, wp_register_style() should probably be called to include the style sheets (though I’m being a perfectionist when I mention this).

        My suggested alternatives to your functions:
        http://pastebin.com/mH2mgkSb

        All that aside I am looking forward to playing with jQplot and your code.

        • http://www.wp-tricks.co.il/ rami

          +1.

  • Pingback: My tutorials in Wptuts « Webania.net – Yet another web developer blog

  • http://twitter.com/drale2k Drazen Mokic

    If you ever change the nam of your plugin and with that the folder name, you will need to edit the paths used in wp_register_script() if you you use that bloginfo(‘wpurl’) method.

    Instead, you can do

    wp_register_script(‘somescript’, plugins_url(‘somescript.js’, __FILE__));

    __FILE_ is a magic constant which will point to the file included.

    • http://www.damiencarbery.com Damien

      @Drazen: I saw __FILE__ used in the plugins_url() docs. I didn’t use that because I think that this tutorial puts the code in functions.php (though not explicitly stated) rather that in a file in the infograph plugin directory. My assumption could, of course, be wrong.

  • Pingback: Mostrar información de tu sitio web WordPress utilizando gráficos con jQuery | SummArg

  • Pingback: WordPress Dashboard & Meta Box Customization Resource | ChurchMag

  • Pingback: Wordpress News - The Best WordPress Tips and Tutorials of 2011Wordpress News

  • Pingback: WordPress Year in Review: The Best Tutorials of 2011 | Simpler Design's

  • Pingback: Bangladesh Web Lab | Bangladeshi Web Designer and Developer Blogs – Best WordPress Tips and Tutorials of 2011

  • Pingback: WordPress Arena: A Blog for WordPress Developers, Designers and Blogger

  • Pingback: 16 Useful jQuery Tutorials to Enhance your WordPress Site

  • Pingback: WordPress: The Best of 2011 and Future Predictions | Wptuts+

  • Will Taylor

    When I call this function somewhere, I get a warning:
    Warning: Missing argument 1 for categories(). Which argument to pass?

    • Will Taylor

      Can anyone tell me which value does $atts argument contain?