matomo-org / matomo-for-wordpress

Get a fully functioning Matomo Analytics for your WordPress. Star us on Github? +1. Matomo is the leading open alternative to Google Analytics that gives you full control over your data. Privacy is built-in. 100% data ownership, no one else can see your data. We love Pull Requests!
https://matomo.org
GNU General Public License v3.0
119 stars 25 forks source link

Hook into Hit-Tracking #1099

Open djstini opened 7 months ago

djstini commented 7 months ago

Hi,

is there a way to trigger a custom action on every visit that is filtered/tracked by Matomo?

Couldn't find anything on that in the Documentation https://developer.matomo.org/api-reference/wordpress/hooks-reference#filters

diosmosis commented 7 months ago

Hi @djstini, there's currently no WordPress specific hook, though it shouldn't be too hard to add. Can you explain your intended use case? What would you use such a hook for?

djstini commented 7 months ago

Hi @diosmosis my Use-Case is the following:

We are using Matomo for the general tracking of the site. As Matomo includes mechanisms to filter out bots etc. i would like to leverage this filtering in order to create, for example, custom metrics.

Let's say for example whenever a "real" visitor visits a page I want to update a post-meta.

diosmosis commented 7 months ago

@djstini for something that generic, it sounds like you might be better served by creating a custom Matomo plugin, and having that installed in WordPress. Is that a solution that might work for you? (Note: you would want to look at the RequestProcessor API, https://developer.matomo.org/guides/tracking-requests. You'd create a new one in a new Matomo plugin, and add your WordPress specific logic to one of the hooks in that class.)

djstini commented 7 months ago

Ahh okay, so i'd just extend on the Matomo-RequestProcessor and add my stuff that way. That sounds doable.

Thanks :3

diosmosis commented 7 months ago

Glad this approach might work for you! One thing to note: for Matomo plugins to be installed as WordPress plugins, the main plugin file needs to have this bit of code at the top:

if (defined( 'ABSPATH')
&& function_exists('add_action')) {
    $path = '/matomo/app/core/Plugin.php';
    if (defined('WP_PLUGIN_DIR') && WP_PLUGIN_DIR && file_exists(WP_PLUGIN_DIR . $path)) {
        require_once WP_PLUGIN_DIR . $path;
    } elseif (defined('WPMU_PLUGIN_DIR') && WPMU_PLUGIN_DIR && file_exists(WPMU_PLUGIN_DIR . $path)) {
        require_once WPMU_PLUGIN_DIR . $path;
    } else {
        return;
    }
    add_action('plugins_loaded', function () {
        if (function_exists('matomo_add_plugin')) {
            matomo_add_plugin(__DIR__, __FILE__, true);
        }
    });
}

This isn't documented anywhere as far as I know, since it's automatically added by Matomo marketplace. You'll have to add it yourself.

I'll keep this issue open as I imagine WordPress hooks would be more convenient for some use cases.