When creating a listing page, it’s often necessary to offer users the ability to sort items by popularity based on the number of views of each page. This helps highlight content that is more likely to interest them.
The Statistics Module in Drupal
To achieve this, Drupal offers the Statistics module, which is currently included in core. This module allows you to store the number of daily views on a node, as well as views since its creation.
Once installed and configured, you just need to create a View that uses the data collected by the module as a sorting criterion, and you’re good to go.
Although this solution is straightforward to implement and well-documented, it has some weaknesses related to the Statistics module:
- Only daily views and views since the node's creation are recorded, so it’s impossible to sort articles more granularly by custom date ranges (e.g., week, month, year, etc.).
- It is difficult to filter which views should be counted, for example, excluding views by the developer working on the project.
The Plausible Pageviews Module
To overcome these limitations, I created the Drupal Plausible Pageviews module, which retrieves page view counts directly from Plausible Analytics and saves them on your site.
This module is open-source and available on GitHub: https://github.com/jverneaut/drupal-plausible-pageviews
Here’s how it works:
- After installation and configuration, add the new
Plausible Pageviews
field provided by the module to each content type for which you want to synchronize view counts with Plausible Analytics. - When the Drupal CRON task runs:
- The module retrieves the page view counts from the Plausible Analytics API.
- It finds the content associated with the URLs returned by the API.
- It updates the view count for each content item that has a
Plausible Pageviews
field.
By doing this, the data you retrieve are the actual site traffic data.
By adjusting the period for which data is retrieved, you can easily sort the most popular pages on your site by a period of a week, month, or year.
Since Plausible Analytics becomes the source of the data, you can benefit from its filtering system based on IP address, country, browser, or page group to avoid artificially inflating view counts while working on your own site.
In the case of a migration to Drupal, it also becomes possible to keep a previous sort by popularity if the previous site already used Plausible Analytics and the structure of the URLs between the two is unchanged.
Limitations and Improvements
This module was created to meet my specific needs, so it has some limitations detailed on its GitHub page related to my particular use case. If your needs differ, I encourage you to explore its source code and modify the hundred or so lines that contain the core functionality to adapt it to your needs.