putyourlightson / craft-entry-count

Counts and displays the number of times that an entry has been viewed in Craft CMS.
MIT License
47 stars 19 forks source link

Ordering by Entry Count #13

Closed ghost closed 6 years ago

ghost commented 6 years ago

I may be missing something, but is there a way to sort entries by count?

putyourlightson commented 6 years ago

They should by default be ordered by count, are you seeing something different when using this code?

{% set entries = craft.entryCount.entries.all() %}

ghost commented 6 years ago

Ahh, I see - I wanted to use the craft.entries tag and then order it - I need to be able to sort by the count including entries that don't have a count yet. Do you think the best way to do that would be hooking into when an entry is saved and adding a zero count row for that entry if it doesn't exist yet?

putyourlightson commented 6 years ago

You'd need to use some twig logic for that. After getting the counted entries, loop through all the entries and only merge entries with a count of 0, so something like this:

{% set sortedEntries = craft.entryCount.entries.all() %}
{% set entries = craft.entries.all() %}

{% for entry in entries %}
  {% if craft.entryCount.getCount(entry.id).count == 0 %}
    {% set sortedEntries = sortedEntries|merge([entry]) %}
  {% endif %}
{% endfor %}