2

Please tell me how to make the number of article views? Is there some free plugin or something else? Or does Craft CMS already have some kind of built-in tool for these purposes?

2
  • Please don't include "Craft CMS" in the title, this entire site is about Craft CMS. It is redundant and unnecessary to include the CMS name in the title of every post.
    – Lindsey D
    Commented Dec 17, 2022 at 16:48
  • Similarly, I'd highly recommend adding more tags beyond the basic craft3 tag. Each of your posts is tagged with only craft3, which limits their visibility. Consider adding tags which are relevant to the subject of the question.
    – Lindsey D
    Commented Dec 17, 2022 at 16:51

2 Answers 2

1

You can use the core seq() Twig function for this:

<p>This article has been viewed {{ seq('pageviews:' ~ entry.id) }} times</p>

If you want to render the current view count without incrementing it, you can pass next=false to the seq() function. A common use case is doing this conditionally, for example to avoid logged-in users (i.e. content authors) from incrementing the count:

{# Only increment the view count if the user is not logged in #}
{% set incrementPageViews = currentUser is null %}

<p>This article has been viewed {{ seq('pageviews:' ~ entry.id, next=incrementPageViews) }} times</p>

Make sure to avoid putting the seq() function inbetween {% cache %} tags! If you do need to cache the surrounding output, a workaround is using a placeholder string inside the cache, and replacing that cached placeholder for the live output from the seq() function:

{# Set the page views to a variable
{% set pageviews = seq('pageviews:' ~ entry.id) %}

{# Use the replace filter to swap out the cached placeholder string for the live pageviews #}
{% apply replace('%PAGEVIEWS%', pageviews) %}

    {% cache %}
        <p>This article has been viewed %PAGEVIEWS% times</p>
    {% endcache %}

{% endapply %}
1
  • It worked! The counter is working, but I tried to display the number of views in the news list like this: {% for new in news %} {{ new.title }} ({{ seq('pageviews:' ~ new.id, next=false) }})<br /><br />{% endfor %} The code is triggered, a list of news is displayed. But in the news list, each entry has zero views. And also, is it possible to sort by the number of views? Please complete the solution if it is not difficult for you))
    – Dimi
    Commented Dec 19, 2022 at 16:01
1

Found a solution! Used a plugin "Entry Count". Great thing https://putyourlightson.com/plugins/entry-count

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.