Create Custom WooCommerce Report

Create Custom WooCommerce Report

When running a business, reports are very important. WooCommerce is one of the leading eCommerce solution and it includes some simple and nice reports like sales by date, products, categories, taxes, etc. But, sometimes they are not enough or the client may want to have some additional data. Lets say the client wants to have sales report by country and to be able to filter it by date.

There are multiple styles for showing the reports (line chart and pie chart), but we’re going to leave that for some other blog post. Today, we’re going to build a simple table report.

At the very beginning, we will need to include the WC_Admin_Report class. This can be done by including the class-wc-admin-report.php file, which is shown on the first line in the code below.

Also, we will need to create a “Sales By Country” page under the “Orders” tab in WooCommerce Reports. To accomplish this, we will use the woocommerce_admin_reports filter as shown below.

If you look at the source code, you will see that $reports is an array containing the tabs and it’s pages. Basically, what we do is inserting our page in that array. Note that you can change ‘orders’ to some of the other available tabs: customers, stock or taxes, or to create your own tab.

Next, we’re moving to our callback function where we create an instance of the WC_Report_Sales_By_Country class which we are going to create a bit later and we are calling it’s output_report() method which is displaying the date filter and the table report in our case.

Now, lets get with the real action. We’re going to extend the WC_Admin_Report class and override the two methods that we need: output_report() – to change the default date range and get_main_chart() – query all completed orders for the specified date range, group them by country, display the number of orders and the earnings. The rest of the methods that can be overriden, like the export button, can be found here.

By default WooCommerce is displaying reports for the last month, but we want to change it to the current month. This can be done by changing the $current_range to ‘month’ when we don’t have selected a custom range. Other possible values for this are: last_month, year, 7day and month.

In the get_main_chart() using $query_data we’re querying order’s data where we specify the name of the field we want to include, it’s type (post_data, meta, order_item, order_item_meta), function can be SUM, COUNT or empty and the name is how we’re going to reference to that field.

As you can see from the code, we’re accessing to _billing_country as country (see line 56 and 75).

Woocommerce reports

There are more things that need to be covered. Hopefully I will have time in the upcoming period to write a few more blog posts about extending the WooCommerce Reports.

Have a nice day and thank you for reading! If you have any questions, feel free to write a comment.