Unlimited Plugins, WordPress themes, videos & courses! Unlimited asset downloads! From $16.50/m Advertisement # Using HighCharts in WP-Admin Difficulty:IntermediateLength:LongLanguages: Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn. ## What We Are Going to Do This tutorial is aimed at new WordPress developers who want to get insight into some useful techniques which we can use in our development process. In this tutorial, we're going to make our own simple plugin that will present us data graphically within the WordPress admin. We will use standard WordPress classes and functions to fetch data and then display it graphically in the WordPress admin with the help of a jQuery plugin called HighCharts. We will prepare our basic plugin, add a page for it in the wp-admin and then enqueue our plugin's JavaScript only on that page. We will then pass the data that we had fetched to an external script through the use of wp_localize_script. In turn, the script will display our data graphically. The statistics that we plan to show are: 1. Most popular posts 2. Top five categories by number of posts 3. Breakup of categories by posts ## HighCharts According to their site: Highcharts is a charting library written in pure HTML5/JavaScript, offering intuitive, interactive charts to your web site or web application. Highcharts currently supports line, spline, area, areaspline, column, bar, pie, scatter, angular gauges, arearange, areasplinerange, columnrange, bubble, box plot, error bars, funnel, waterfall and polar chart types. You can grab yourself a copy from their website. That said, let's begin working on our plugin. ## Getting Started With Our Plugin ### Initial Setup We will first make a directory inside our wp-content/plugins folder named "admin-charts". Inside that let's make 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 js folder: In the root directory, we will make a index.php file and inside that we will add the initial declaration for our plugin: Now if you go to WP-Admin > Plugins, you will notice that the plugin is being shown there, but it's not functional yet. We will also add some styles inside our admin_charts.css: ### Adding a Plugin Page Our next step would be to add a page for the plugin inside the admin where we would perform all the operations. For that, we will use the WordPress action admin_menu. This action triggers after the basic admin panel menu structure is in place and thus can be used to add more menus or submenus in the admin. The basic usage is as follows: We would add a function chart_add_admin_page inside our index.php and then hook it into this action: Inside our chart_add_admin_page function we will call the native WordPress function add_plugins_page: The first argument is the page title that will be shown in the <title></title> tags of the page. The second argument is the menu title. The third and fourth arguments are the user capability and unique slug for referring to this menu. The last argument is the name of the callback function that will be used to render the contents of this page. Now if you activate the plugin and hover over the "Plugins" menu, you will notice that we have successfully added a menu for our plugin: ### Rendering the Contents of the Plugin Page At this stage, we have successfully added an empty page for our plugin. It's time to make it functional by outputting some content. In our previous call to add_plugins_page we have referred to a callback function render_admin_charts_page. This is the function we have planned to output all the content that we want to have on our page. So let's write the function. Below the chart_add_admin_page function, add the following code: We are just adding some simple HTML here. We have added a heading and a form inside WordPress' native CSS class "wrap". Inside the form, we have added a select box that currently has only one option for showing most popular posts by comment count. Below the form we have added a container div for our charts. Our page is now taking shape: Tip: You should always try to integrate with WordPress' native UI. We have a great series by Stephen Harris covering the topic. It's time to register the necessary scripts and styles so we can enqueue them later. For that, we will use the wp_register_script and wp_register_style function that work in collaboration with the action hook admin_enqueue_scripts if we want to enqueue them on the admin side. But before that, let's add a constant for our plugin root directory so we can refer to it later when we are defining paths for our scripts and styles. So, at the top of the page below the plugin declaration, add this bit of code: We can now define our function to register our scripts and styles: First, we have registered the HighCharts script that we had downloaded earlier. We have given it a handle "highCharts". For the next argument, we have defined the path where it exists. Next, we have passed an array of scripts upon which our script depends, in this case it's jQuery since we would be manipulating the DOM through jQuery. In this way, we won't have to worry about enqueuing jQuery, it will be enqueued automatically whenever we enqueue the highCharts script. For the third argument, we have defined a version number and for the last argument, we have told the wp_register_script to enqueue the script in the footer of the page after the main content. In the same way, we have registered our second script where we would be adding all of our necessary JavaScript code. We can now actually enqueue our scripts and styles on our plugin page, but we don't want them to be enqueued on every single page in the admin where they are not needed. For that reason, we will check for a condition before we enqueue our scripts: The function that we hook with admin_enqueue_scripts actually receives a parameter for the admin page that we are currently on. In our case, it's "plugins_page_admin-charts". You can always check this parameter by echoing it in your development process. Now that we have prepared a base for our plugin, we can begin working on our core objective i.e. fetching data and displaying statistics. ## Fetching and Displaying Statistics We want to fetch three types of data: 1. Most popular posts (column chart) 2. Top five categories by number of posts (column chart) 3. Breakup of categories by posts (pie chart) ### Most Popular Posts For this type of data, we can use the WP_Query class to fetch five posts that have the highest number of comments. The WP_Query class comes in handy when we need to fetch posts based on different criteria. Using this class, we can list posts in any way we want. The query for fetching posts with the highest number of comments can be written as: We now have five posts that have the highest number of comments, in the form of objects inside the $posts array. You can always echo the variable to see what you are working with.

We need to pass this object along with other essential data to the JavaScript. For that purpose, we will first prepare an array that will contain the data type, the chart type that we need to draw, and finally the posts that we have just fetched through WP_Query.

We can pass this variable to JavaScript through wp_localize_script:

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

But we need to make sure that WP_Query and wp_localize_script only get called when we have submitted the form; therefore, we are enclosing them inside another if statement that checks if the form has been submitted:

The only thing left now is to grab the data inside our JavaScript file and draw the chart. Inside the js/admin_charts.js file, add the following code:

The \$data array we had passed through index.php has turned into an object inside JavaScript. We can thus manipulate it like any other JavaScript object.

We are first checking for the data type that's coming in:

Then we have initialized two empty arrays for post titles and post comment count respectively:

And finally we have iterated through the posts and grabbed the titles and comment count in the arrays we have initialized:

Now it's time to actually draw the chart using the data we have fetched, for that we have used the HighCharts API:

Now go back to your Plugins > Admin Charts and after selecting an option from the drop down, click the submit button, you should now have a working column chart.

You might want to go back to your posts, add some comments and then come back to see the updated statistics:

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

### Top Five Categories by Number of Posts

All we have to do now is to get five categories that have the highest number of posts associated. But before that, let's add an option for this data type in our select dropdown. So go back to the render_admin_charts_page function we had defined earlier and update it as follows:

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

We then fetch our data the same way we had done before:

So the final piece of code should be like this:

In the admin_charts.js, insert this code after the if statement:

We are doing the same thing as before, but this time we have changed the chart title and the captions for the axes. We should now have another chart displaying the top five categories with most number of posts:

### Breakup of Categories by Posts

Our last data type is the breakup of categories by number of posts. For this type of data, we will use the pie chart as it's most appropriate in this case. Also note that a single post might belong to multiple categories.

We will use the same get_categories function but this time we are not limiting the number of categories we get, instead we need to get all the categories to show the breakup.

So we will begin by checking if the option has been selected for this data type and then call our function to retrieve the categories, prepare our array, and then pass it to the JavaScript:

It's relatively simple to draw a pie chart. In admin_charts.js, add the following code after the existing else-if statement:

Note that we have formatted the tooltip to show percentage instead of an integer. We are almost done except for a little utility function we can add to each of our select options so that it persists when the page loads after submitting the form.

Add this bit of code inside index.php after the render_admin_charts_page function:

And then call the function inside each of our select options:

Our plugin is now completed and you now have three working charts for different types of data. Feel free to play around and add more charts for more data types.

## Conclusion

In this tutorial we made our own plugin from the ground up and added a separate page in the wp-admin. We have also looked at some of the techniques that can be useful when developing for WordPress.

These include different ways to get the required information about the posts and categories and then passing that to the JavaScript so we could use it for different purposes.

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