Modifying Koko Analytics using filter hooks

Certain stuff in the Koko Analytics plugin is not configurable through a dedicated setting on the settings page, but through so-called filter hooks. This is a powerful method to modify the default behavior in the plugin.

First off, if you are already familiar with the way action and filter hooks in WordPress work then we have a collection of sample code snippets to give you some ideas.

Another great way to discover filter hooks is to browse the source code of the plugin itself. This may seem daunting if you’re not familiar with programming in PHP, but it’s something I personally wish I started doing earlier in my career.

Creating a file to add our code snippets to

A filter hook in the context of WordPress development is any value that runs through the apply_filters function. This allows other code on your WordPress site to modify the value of the first argument that is passed.

To add code to your site that uses filter hooks, first create a file in your /wp-content/plugins/ directory and name it something like my-hooks.php. Include the following lines at the top of that file:

<?php

/**
 * Plugin Name: My hooks
 */Code language: HTML, XML (xml)

If you now go into your WP Admin and browse to the Plugins page, you should see a new available plugin called My hooks. After activating it, that file is now loaded on every request to your site.

We can now start adding code to that file.

Adding our first filter hook

Let’s go through an example together.

Koko Analytics comes with a filter hook called koko_analytics_load_tracking_script which allows you to override the default logic that determines whether to load the tracking script for that request.

Let’s say we want to ensure the file is not loaded on 404 requests. We can add a filter on said hook and use the default condition together with the result of the is_404() function to ensure that false is returned whenever the current request is for an unexisting post or page.

<?php

/**
 * Plugin Name: My hooks
 */

add_filter('koko_analytics_load_tracking_script', function($load) {
    return $load && ! is_404();
});Code language: HTML, XML (xml)

That’s all there is to it!

With this snippet in place, the tracking script will no longer be loaded on any 404 pages.

Available filter hooks in Koko Analytics

To give you an idea of the available filter and action hooks in Koko Analytics, we recommend searching the source code of the plugin for apply_filters and going through our example snippets collection.

Was this article helpful? Yes / No