2

I need to save page views for some pages.

I ended up doing it with this code:

{% set pageviews = entry.pageviews %}
{% do entry.setFieldValue('pageviews', pageviews+1) %}
{% do craft.app.getElements().saveElement(entry) %}

It's working fine but it slows down significantly the page with an increase of around 100 database queries which I cannot explain.

Is there a more efficient way of doing this?

1 Answer 1

1

It's natural that you're seeing a lot of extra queries; Craft does a ton of work when saving an entry (creating/pruning revisions, updating search indexes, propagating elements etc). You're probably also going to have your template caches invalidated on every pageload. In short, re-saving entries on every frontend request is a bad idea.

A much better approach is using Craft's seq() function:

{# Increment page views for the current entry, without outputting the current count #}
{% do seq('pageviews:' ~ entry.id) %}

{# Output page views for the current entry, without incrementing #}
{{ seq('pageviews:' ~ entry.id, next=false) }}

{# Increment _and_ output the current count #}
{{ seq('pageviews:' ~ entry.id) }}

The seq() function doesn't interface with custom fields, though. If you do need to have the page view count stored in a custom field for some reason, a possible workaround in terms of the performance issue is going through the Content service to save the updated custom field value instead of actually re-saving the entry using craft.app.getElements():

{% set pageviews = entry.pageviews %}
{% do entry.setFieldValue('pageviews', pageviews+1) %}
{% do craft.app.getContent().saveContent(entry) %}

The above is pretty hacky though, and not really a much better idea than actually re-saving the entry in full (although it does result in less queries being executed). It's definitely not an approach I would recommend.

Finally, there's also a few plugins available for storing view counts, for example this or this.

1
  • 1
    Great thank you so much! I did not know the seq() function, very useful.
    – Samuel
    Commented Mar 7, 2022 at 11:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.