Namecheap.com - Cheap domain name registration, renewal and transfers - Free SSL Certificates - Web Hosting

WordPress Use Chart in Front and Back End Using Chart.js



Charts are so useful now a days, showing charts instead of data table , looks easy and ease of presence. There are so many Chart plugins are available to use. But that  are all not opt to your wordpress blog. So I found a way to use it on my own customization. First of all I tried to use php class for Drawing Charts but. None of that is free and looks nice. So i used Charts.js for drawing charts. It's light weight and create a animated view for drawing chart on your browser.

First you need Chart.min.js is need to use it. It is flexible to customize and it supports 6 types of charts. 

Additionally, excanvas.compiled js package is needed.  download it from Charts.js source site

first of all  enqueue these two files into wordpress, both in admin and front end use.


// Add IE Fallback for HTML5 and canvas
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_html5_support () {
    echo '<!--[if lt IE 8]>'; //this is for the support of HTML 5 which helps to draw chart  
    echo '<script src="'.plugins_url( '/js/excanvas.compiled.js', __FILE__ ).'"</script>';
    echo '<![endif]-->';
    echo ' <style>
    /*wp_charts_js responsive canvas CSS override*/
    .wp_charts_canvas {
    width:100%!important;
    max-width:100%;
    height:auto!important;
    }
    </style>';
}

// Register both  Scripts 
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_load_scripts() {

if ( !is_Admin() ) {
wp_register_script( 'charts-js', plugins_url('/js/Chart.min.js', __FILE__) );
wp_enqueue_script( 'charts-js' );
}
}
add_action( "wp_enqueue_scripts", "wp_charts_load_scripts" );
add_action('wp_head', 'wp_charts_html5_support');


here html support is used under wp_head to initiate the js function

 You can use color conversion and  showing of different color variations from this code

// make sure there are the right number of colours in the colour array
// - - - - - - - - - - - - - - - - - - - - - - -
if ( !function_exists('wp_charts_compare_fill') ) {
function wp_charts_compare_fill(&$measure,&$fill) {
// only if the two arrays don't hold the same number of elements
if (count($measure) != count($fill)) {
   // handle if $fill is less than $measure
   while (count($fill) < count($measure) ) {
       $fill = array_merge( $fill, array_values($fill) );
   }
   // handle if $fill has more than $measure
   $fill = array_slice($fill, 0, count($measure));
}
}
}

// color conversion function
// - - - - - - - - - - - - - - - - - - - - - - -
if (!function_exists( "wp_charts_hex2rgb" )) {
function wp_charts_hex2rgb($hex) {
  $hex = str_replace("#", "", $hex);

  if(strlen($hex) == 3) {
     $r = hexdec(substr($hex,0,1).substr($hex,0,1));
     $g = hexdec(substr($hex,1,1).substr($hex,1,1));
     $b = hexdec(substr($hex,2,1).substr($hex,2,1));
  } else {
     $r = hexdec(substr($hex,0,2));
     $g = hexdec(substr($hex,2,2));
     $b = hexdec(substr($hex,4,2));
  }

  $rgb = array($r, $g, $b);
  return implode(",", $rgb); // returns the rgb values separated by commas
}
}


data trailing function for serialize your data 

if (!function_exists('wp_charts_trailing_comma')) {
function wp_charts_trailing_comma($incrementor, $count, &$subject) {
$stopper = $count - 1;
if ($incrementor !== $stopper) {
return $subject .= ',';
}
}
}

Here we ready to draw a chart. We almost done except the function to give raw data for drawing a chart.  We have to give the parameters of the chart, i.e values to draw a chart .  Which type of chart we are going to use here. I already specified that chart.js supports 6 types of charts.
For example I use Pie Chart here.

array(
'type'             => 'pie',  //type of chart we are going to use
'title'            => 'chart',
'canvaswidth'      => '625',
'canvasheight'     => '625',
'width' => '48%',
'height' => 'auto',
'margin' => '5px',
'align'            => '',
'class' => '',
'labels'           => '',
'data'             => '30,50,10', //data for drawing a chart
'datasets'         => '30,50,100 next 20,90,75',   
'colors'           => '69D2E7,#E0E4CC,#F38630,#96CE7F,#CEBC17,#CE4264',
'fillopacity'      => '0.7',
'pointstrokecolor' => '#FFFFFF' );

 The above array contains a list of parameters for the chart. 


// Chart Shortcode 1
// - - - - - - - - - - - - - - - - - - - - - - -
function wp_charts_shortcode( $atts ) {

// Default Attributes
// - - - - - - - - - - - - - - - - - - - - - - -
extract( shortcode_atts(
array(
'type'             => 'pie',
'title'            => 'chart',
'canvaswidth'      => '625',
'canvasheight'     => '625',
'width'   => '48%',
'height'   => 'auto',
'margin'   => '5px',
'align'            => '',
'class'   => '',
'labels'           => '',
'data'             => '30,50,10',
'datasets'         => '30,50,100 next 20,90,75',
'colors'           => '69D2E7,#E0E4CC,#F38630,#96CE7F,#CEBC17,#CE4264',
'fillopacity'      => '0.7',
'pointstrokecolor' => '#FFFFFF'
), $atts )
);

// prepare data
$title    = str_replace(' ', '', $title);
$data     = explode(',', str_replace(' ', '', $data));
$datasets = explode("next", str_replace(' ', '', $datasets));
$colors   = explode(',', str_replace(' ','',$colors));
(strpos($type, 'lar') !== false ) ? $type = 'PolarArea' : $type = ucwords($type) ;

// output - covers Pie, Doughnut, and PolarArea
$currentchart = '<div class="'.$align.' '.$class.'" style="width:'.$width.';height:'.$height.';margin:'.$margin.';">';
$currentchart .= '<canvas id="'.$title.'" height="'.$canvasheight.'" width="'.$canvaswidth.'" class="wp_charts_canvas"></canvas></div>
<script>';

// start the js arrays correctly depending on type
if ($type == 'Line' || $type == 'Radar' || $type == 'Bar') {

wp_charts_compare_fill($datasets, $colors);
$total    = count($datasets);

// output labels
$currentchart .= 'var '.$title.'Data = {';
// if ( count($labels) > 0 ) {

$currentchart .= 'labels : [';
$labelstrings = explode(',',$labels);
// wp_charts_compare_fill($datasets, $labelstrings);
for ($j = 0; $j < count($labelstrings); $j++ ) {
$currentchart .= '"'.$labelstrings[$j].'"';
wp_charts_trailing_comma($j, count($labelstrings), $currentchart);
}
$currentchart .= '],';
// }

$currentchart .= 'datasets : [';
} else {
wp_charts_compare_fill($data, $colors);
$total = count($data);

$currentchart .= 'var '.$title.'Data = [';
}
// create the javascript array of data and attr correctly depending on type
for ($i = 0; $i < $total; $i++) {

if ($type === 'Pie' || $type === 'Doughnut' || $type === 'PolarArea') {

$currentchart .= '{
value : '. $data[$i] .',
color : '.'"'. $colors[$i].'"'.'
}';

} else if ($type === 'Bar') {

$currentchart .= '{
fillColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .','.$fillopacity.')",
strokeColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
data : ['.$datasets[$i].']
}';

} else if ($type === 'Line' || $type === 'Radar') {

$currentchart .= '{
fillColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .','.$fillopacity.')",
strokeColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
pointColor : "rgba('. wp_charts_hex2rgb( $colors[$i] ) .',1)",
pointStrokeColor : "'.$pointstrokecolor.'",
data : ['.$datasets[$i].']
}';

}  // end type conditional
wp_charts_trailing_comma($i, $total, $currentchart);
}
// end the js arrays correctly depending on type
if ($type == 'Line' || $type == 'Radar' || $type == 'Bar') {
$currentchart .= ']
};';
} else {
$currentchart .= '];';
}
$currentchart .='var wpChart'.$title.$type.' = new Chart(document.getElementById("'.$title.'").getContext("2d")).'.$type.'('.$title.'Data);
</script>';
// return the final result
return $currentchart;
}

give parameter through $atts and draw your chart. if you have questions comment below.

2 Responses to “ WordPress Use Chart in Front and Back End Using Chart.js”

Unknown said...
14 July 2017 at 18:11

custom scoreboard, auto load posts, 4 different pre-defined skins, 9 different options featured posts, 8 different article templates, 700+ Google fonts, and so much more !
Premium wordpress themes


Blogger Cage said...
21 June 2020 at 10:08

your guidence is appreciated.I save more time by avoiding errors and work smoothly, this is because of you.WordPress Errors.Keep sharing.Thanks a lot.


Post a Comment

Namecheap.com - Cheap domain name registration, renewal and transfers - Free SSL Certificates - Web Hosting