HighCharts How to add series via an array

Using HighCharts in WP-Admin

Charts are a great way to present data. They make data easier to digest by making it visually appealing. There is no built-in method in WordPress for getting posts and page data in graphical form.

While there are certain plugins that integrate Google Analytics with WordPress, they are overkill if you only want to get some of that data.

Nothing should stop you from learning new techniques, and diving straight into the subject is the best way to learn.


What we will do

This tutorial is for new WordPress developers who want to gain insight into some useful techniques that we can use in our development process. In this tutorial we will create our own simple plugin that graphically displays data within the WordPress administrator. We will be using standard WordPress classes and functions to retrieve data and then graphically display it in the WordPress admin using a jQuery plugin called HighCharts.

We prepare our basic plug-in, add a page in the Wp-Admin and then only enter the JavaScript of the plug-in on this page. We will then pass the data that we have retrieved to an external script using. The script in turn shows our data graphically.

The statistics we want to show are:

  1. The most popular posts
  2. Top five categories by number of posts
  3. Division of the categories according to contributions

HighCharts

According to their website:

Highcharts is a diagram library written in pure HTML5 / JavaScript that provides intuitive, interactive diagrams for your website or web application. Highcharts currently supports line, spline, area, area, column, bar, pie, scatter, angle displays, areas, area differences, column areas, bubbles, box diagrams, error bars, funnel, waterfall and polar diagram types.

You can get a copy from their website.

Let's start working on our plugin.


First steps with our plugin

initial setup

We're going to create a directory in ours first WP content / plugins Folder named "Admin diagramsInside we create the initial directory structure for our plugin.

Copy the file highcharts.js from the directory in the zip file you downloaded from the official website to a directory js Portfolio:

In the root directory we will be a index.php File and in it we will add the first declaration for our plugin:

If you now go to WP-Admin> Plugins, you will find that the plugin is displayed there, but is not yet functional.

We'll be adding some styles to ours too admin_charts.css:

#admin_chart_form margin: 30px 0; #admin_chart_form label display: inline block; Width: 250px;

Adding a plugin page

Our next step would be to add a page for the plugin in the admin where we would do all the operations. We use the WordPress campaign for this. This action is triggered after the basic menu structure of the admin panel is in place. It can therefore be used to add further menus or submenus in the admin. The basic usage is as follows:

We'd add a feature in our index.php and hook it up to this action:

add_action ('admin_menu', 'chart_add_admin_page');

In our function we call the native WordPress function:

function chart_add_admin_page () add_plugins_page ('Diagrams for Wordpress', 'Admin Diagrams', 'Administrator', 'Admin Diagrams', 'render_admin_charts_page');

The first argument is the page title, which will appear in the page's tags. The second argument is the menu title. The third and fourth arguments are usability and the unique slug to refer to this menu. The final argument is the name of the callback function that will be used to render the contents of this page.

If you now activate the plugin and move the mouse pointer over the "Plugins" menu, you will see that we have successfully added a menu for our plugin:

Render the content of the plugin page

At this point we have successfully added a blank page for our plugin. It is time to make it work by delivering content.

In our previous call to We referred to a callback feature. This is the function we have planned to output all the content that we would like to have on our page. So we write the function.

Under the function, add the following code:

Function render_admin_charts_page ()?> Var13 ->

We're just adding some simple HTML here. We added a heading and a form to WordPress' native CSS class. ".

Within the form, we've added a selection box that currently only has an option to view the most popular posts by number of comments. Below the form we have added a container for our charts.

Our site is now taking shape:

Top: You should always try to integrate the native WordPress user interface. We have a great series by Stephen Harris on the subject.

It's time to register the scripts and styles we need so we can pop them in later. For this we use the and functions that work together with the action hook when we want to include them on the admin page.

But first, let's add a constant for our plugin root directory so that we can refer to it later when we define paths for our scripts and styles. At the top of the page below the plug-in declaration, add the following code bit:

define ('ROOT', plugin_dir_url (__FILE__));

We can now define our function to register our scripts and styles:

add_action ('admin_enqueue_scripts', 'chart_register_scripts'); function chart_register_scripts () wp_register_script ('highCharts', ROOT. 'js / highcharts.js', array ('jquery'), '3.0', true); wp_register_script ('adminCharts', ROOT. 'js / admin_charts.js', array ('highCharts'), '1.0', true); wp_register_style ('adminChartsStyles', ROOT. 'css / admin_chart.css');

First of all, we registered the HighCharts script that was previously downloaded. We gave it a grip "For the next argument we defined the path in which it exists.

Next, we passed in a number of scripts that our script relies on. In this case it is jQuery because we would be manipulating the DOM through jQuery. This way we don't have to worry about queuing jQuery, it will be automatically queued when we run the script.

For the third argument we have defined a version number and for the last argument we have the script in the footer of the page after the main content. In the same way, we registered our second script, into which we would paste all of our JavaScript code.

We can now actually queue our scripts and styles on our plugins page, but we don't want them to be queued on every single admin page where they are not needed.

This is why we check to see if there is a condition before we record our scripts:

add_action ('admin_enqueue_scripts', 'chart_add_scripts'); function chart_add_scripts ($ hook) if ('plugins_page_admin-charts' == $ hook) wp_enqueue_style ('adminChartsStyles'); wp_enqueue_script ('adminCharts');

The function we are connecting to actually receives a parameter for the administration page we are currently on. In our case it is "". You can always check this parameter by repeating it in your development process.

Now that we've got a base ready for our plugin, we can start working on our core goal of getting data and showing statistics.


Get and display statistics

We want to get three types of data:

  1. Most Popular Posts (Bar Chart)
  2. Top five categories by number of posts (bar chart)
  3. Division of the categories according to contributions (pie chart)

The most popular posts

For this kind of data we can use the class to get five posts with the highest number of comments. The one class comes in handy when we have to retrieve articles according to various criteria. With this class we can list posts arbitrarily. The query to get posts with the highest number of comments can be written as follows:

$ posts = new WP_Query (array ('post_type' => 'post', 'orderby' => 'comment_count', 'order' => 'DESC', 'posts_per_page' => 5));

We now have five posts with the highest number of comments in the form of objects in the array. You can view the variable at any time to see what you are working with.

We need to pass this object to JavaScript along with other important data. To do this, we will first prepare an array that will contain the data type, the type of chart we need to draw, and finally the posts that we have just passed through.

$ data = array ('data_type' => 'chart_most_popular', 'chart_type' => 'column', 'post_data' => $ posts-> posts);

We can pass this variable to JavaScript:

wp_localize_script ('adminCharts', 'data', $ data);

The first argument in the function call is the handle of the script to which we need to pass the data. We had previously registered this script. The second argument is the name of the object that will be available in JavaScript and the last argument is the data itself that we need to pass. The final index.php should look like this:

But we have to make sure of that and you will not be called until we have sent the form. So we're wrapping it up in another statement that verifies that the form has been submitted:

if (isset ($ _POST ['show_chart']))) if ('chart_most_popular' == $ _POST ['chart_data_type']) $ posts = new WP_Query (array ('post_type' => post ',' orderby ') = > 'comment_count', 'order' => 'DESC', 'posts_per_page' => 5)); $ data = array ('data_type' => 'chart_most_popular', 'chart_type' => 'column', 'post_data' => $ posts-> posts); wp_localize_script ('adminCharts', 'data', $ data);

Now all you have to do is pack the data into our JavaScript file and draw the diagram. In the js / admin_charts.js File, add the following code:

(Function ($) if ('chart_most_popular' == data.data_type) var post_titles = [], post_comment_count = []; $ (data.post_data) .each function () post_titles.push (this.post_title) post_comment_count.push ( parseInt (this.comment_count));); $ ('# chart-stats'). highcharts (chart: type: data.chart_type), Title: Text: 'Most Popular Posts (by Number of Comments)', xAxis: categories: post_titles, yAxis: title: text: 'Number of Comments', Series: [Name:' Number of comments', data: post_comment_count]); (jQuery));

The array we went through index.php turned into an object in JavaScript. We can therefore manipulate it like any other JavaScript object.

We first check the data type that is going into the database:

if ('chart_most_popular' == data.data_type)

Then we initialized two empty arrays for post titles or the number of comment comments:

var post_titles = [], post_comment_count = [];

And finally, we went through the posts and recorded the titles and number of comments in the arrays we initialized:

$ (data.post_data) .each (function () post_titles.push (this.post_title); post_comment_count.push (parseInt (this.comment_count)););

Now is the time to draw the graph using the data we have retrieved. We used the HighCharts API for this:

$ ('# chart-stats'). highcharts (chart: type: data.chart_type, title: text: 'Most popular posts (by number of comments)', xAxis: categories: post_titles, yAxis: title: text: 'number of comments', series: [name:' number of comments', data: post_comment_count]);

Now go back to your Plugins> Admin Diagrams and after selecting an option from the drop-down list click the "Submit" button. You should now have a working column chart.

You may want to go back to your posts, add comments, and then come back to see the updated stats:

We can now add support for more data types in our plugin.

Top five categories by number of posts

Now all we have to do is get five categories that have the highest number of posts. But first, let's add an option for this data type to our drop-down list. So go back to the previously defined function and update it like this:

We can use the native WordPress function and pass some arguments:

$ categories = get_categories (array ('orderby' => 'count', 'order' => 'desc'));

We then retrieve our data in the same way as before:

$ data = array ('data_type' => 'chart_top_cat', 'chart_type' => 'column', 'post_data' => $ categories);

So the last piece of code should look like this:

if ('chart_cat_break' == $ _POST ['chart_data_type']) $ categories = get_categories (array ('orderby' => 'count', 'order' => 'desc')); $ data = array ('data_type' => 'chart_cat_breakup', 'chart_type' => 'pie', 'post_data' => $ categories); wp_localize_script ('adminCharts', 'data', $ data);

By doing admin_charts.js, Add this code after the statement:

else if ('cart_top_cat' == data.data_type) var cat_titles = [], cat_count = []; $ (data.post_data) .each (function () cat_titles.push (this.name); cat_count.push (parseInt (this.count));); $ ('# chart-stats'). highcharts (chart: type: data.chart_type, title: text: 'Top 5 categories according to posts', xAxis: categories: cat_titles, yAxis: title: text:' number of posts', tickInterval: 5, series: [name: ' Number of contributions', data: cat_count]);

We're doing the same thing as before, but this time we've changed the chart title and labels for the axes. We should now have another chart showing the five main categories with the most posts:

Separation of categories according to contributions

Our final data type is the breakdown of categories based on the number of posts. For this type of data, we will use the pie chart as it is best for this case. Also note that a single post can belong to multiple categories.

We're going to use the same function, but this time we're not limiting ourselves to the number of categories we get, we need to get all of the categories to show the separation.

So we're going to first check that the option for that data type is selected, then call our function to get the categories, prepare our array, and pass it to the JavaScript:

if ('chart_cat_breakup' == $ _POST ['chart_data_type']) $ categories = get_categories (array ('orderby' => 'count', 'order' => 'desc')); $ data = array ('data_type' => 'chart_cat_breakup', 'chart_type' => 'pie', 'post_data' => $ categories); wp_localize_script ('adminCharts', 'data', $ data);

It's relatively easy to draw a pie chart. in the admin_charts.js, Add the following code after the existing statement:

else if ('chart_cat_breakup' == data.data_type) var number_posts = []; $ (data.post_data) .each (function () number_posts.push ([this.name, parseInt (this.count)]);); $ ('# chart-stats'). highcharts (title: text: 'Division of the categories according to the number of posts'), Tooltip: pointFormat:' Number series.name: point.y
series.name release: point.percentage: .1f%', series: [type:' pie ', name:' Posts', data: number_posts]);

Notice that we've formatted the tooltip to show the percentage instead of an integer. We're almost done, with the exception of a little helper feature that we can add to any of our choices so that even after submitting the form it will persist when the page loads.

Add this bit of code index.php according to the function:

Function selected_option ($ option) if ($ otpion == $ _POST ['chart_data_type']) echo 'selected = "selected"';

Then call the function in each of our selection options:

Our plugin is now complete and you now have three working diagrams for different data types. Feel free to play around and add more graphs for more data types.


Conclusion

In this tutorial we created our own plugin from scratch and added our own page to the WP-Admin. We also looked at some techniques that can be useful when developing for WordPress.

This includes various methods of getting the required information about the posts and categories and then passing it to JavaScript so we can use it for different purposes.

I hope you found this tutorial useful and don't forget to leave your constructive feedback in the comments.