Sort by most viewed
You can sort your results to display the most viewed elements first.
Fetch your Element Query (opens new window) just as you normally would, then pass the Element Query into the sort
method.
{% set articles = craft.entries.section('articles') %}
{% do craft.viewCount.sort(articles) %}
If you want to sort by a specific key, simply add it as the second parameter...
{% do craft.viewCount.sort(articles, 'articleRead') %}
Views can be assigned to any valid element type, whether it's native or 3rd party.
Must be an Element Query
Don't apply the .all()
method until after you have sorted the Element Query.
# Pagination
When paginating (opens new window) the results, be sure to pass a query into the paginate
tag:
{# Create a query #}
{% set query = craft.entries()
.section('articles')
.limit(10) %}
{# Order query by most viewed #}
{% do craft.viewCount.sort(query) %}
{# Paginate results #}
{% paginate query as pageInfo, pageEntries %}