4

I am trying to show a list of users but only if they have created a post in a certain section... the code I am using isn't working as expected. Perhaps I have the syntax wrong when it comes to the user model

Help would be greatly appreciated.

{% set entries = craft.entries.section('news') %}
{% set authorList = craft.users.relatedTo(entries) %}

{% for author in authorList %}
<h5><a href="/news/author/{{author.username}}">{{author.fullName}}</a></h5>
{% endfor %}         

2 Answers 2

2

This should do it:

{# Grab all the entries for the section #}
{% set entries = craft.entries.section('news').find() %}

{# Group by the authorId #}
{% set entriesByAuthor = entries|group('authorId') %}

{# Grab all of the users with the userIds in entriesByAuthor #}
{% set authors = craft.users.id(entriesByAuthor|keys) %}

<ul>
    {% for author in authors %}
        <li>{{ author.username }}
    {%  endfor %}
</ul>
1
  • 1
    Awesome, thanks as always!! Why doesn't it work with the usual relatedTo parameter? Commented Aug 21, 2014 at 14:42
1

This is similar to another question, and should yield the same results:

{% set entryIds = craft.entries.section('news').ids() %}
{% set authorList = craft.users.relatedTo({ sourceElement: entryIds }).find() %}

With this you are basically saying, "I'm looking for users related to these news entries where the news entry is where the user is set".

2
  • 1
    I tried a version like that previously and I also just tested the snippet above and it isn't working : ( That is definitely how I would expect it to work... that's why I thought maybe there was something I was missing. Commented Jul 24, 2014 at 13:07
  • This only works with a user relationship field on the entry, or a entries relationship field on the user. This does not work for the Author field on entries. Commented Jun 4, 2020 at 3:53

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.