Take the 2-minute tour ×
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It's 100% free, no registration required.

I would like to have a Top 10 Tags list in descending order. I'm able to list and limit 10 tags used, but the order parameters are limited to name, group, and date essentially.

share|improve this question
    
just as an FYI, I did set a count but trying order(count desc) doesn't do a thing. :P Because I don't think that's "allowed"? –  lealea Jul 14 at 22:33
1  
count isn't a property of craft.tags. I'm working on it though, after your last question about tag clouds! –  Matt Stein Jul 14 at 23:02
    
If you aren't in a hurry lea, you better wait for @matt's plugin. You can do lots of things with twig, but it's a template language and such thing like my code below are actually considered bad practice! –  carlcs Jul 14 at 23:29

1 Answer 1

This is based on Matt's answer to your previous question. Likewise this should better be used within cache tags!

This is untested, but it hopefully works out for you.

.

Edit:

This is still untested but it came to my ears, that it could make problems to assign variables as array keys. That's why I changed the code to use objects instead. If anyone uses this code, I'd be happy to hear if it does actually work!

{# Get all tags #}
{% set allTags = craft.tags.find() %}

{# Define object outside the for loop #}
{% set weightedTags = [] %}

{# Iterate over all tags #}
{% for tag in allTags %}

    {# Get total number of tag occurrences in entries belonging to 'blog' section #}
    {% set count = craft.entries.section('blog').relatedTo(tag).total() %}

    {# Save tag id and count to our weightedTags object #}
    {% set weightedTags = items|merge([{ tagId: tag.id, tagCount: count }]) %}

{% endfor %}

{# Sort, reverse-sort and pick top 10 elements of the array #}
{% set weightedTags = weightedTags|sort|reverse|slice(0, 10) %}

{# To print the top 10 list iterate over our weightedTags array #}
{% for tagObject in weightedTags %}

    {# Get tag object for each tagId #}
    {% set tagEntry = craft.tags.id(tagObject.tagId).first() %}

    {# Return the list item #}
    <a href="/entries/{{ tagEntry.slug }}" data-count="{{ tagObject.tagCount }}">{{ tagEntry.name }}</a>

{% endfor %}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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