Matomo - "views" method for $page

Hello everyone,

For my blog, I would like to filter my articles according to the most viewed. For this, I was thinking of getting this information from the Matomo plugin. It shows the page views in the panel for each individual page, but I haven’t found a way to load this info into a variable.

The optimal way would be something like “$page->matomoViews()”, but I’m pretty sure, there is no official method for that.

Thanks a lot for your help!

The plugin just displays information it gets from your Matomo instance, so none of this information is stored locally.

You can probably use the routes the plugin comes with to get the data you need. Then it would probably make sense to cache it, so you don’t make a call to the API every time you want to show your articles.

Thank you. I was hoping to get arround this, not beeing very experienced in PHP.

I’ll dig thorugh matomo and if I find a solution, I’ll post it here.

Took me quite a few hours, but finally I managed to get the result, I hoped for!

// get visitors from Matomo
$matomo  = new Matomo();
$content = $matomo->apiPageMetrics(
    'year', // day, week, month, year, range
    $page->uri(),
    [
        'multilang' => '',
        'overview'  => '',
        'default'   => '',
        'current'   => '',
    ]
);

if (empty($content)) {
    $content = array('status' => 'empty');
}

// write visitors to .txt
if (isset($content['current']['visits'])) {
    $page->update([
        'visitsyear' => $content['current']['visits']
    ]);
    
    print_r($content['current']['visits']);
}