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 %}         
Alan Miller
  • 780
  • 5
  • 12

2 Answers2

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>
zizther
  • 449
  • 2
  • 17
Brad Bell
  • 67,440
  • 6
  • 73
  • 143
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".

Bryan Redeagle
  • 4,065
  • 13
  • 27
  • 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. – Alan Miller Jul 24 '14 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. – Johan Douma Jun 04 '20 at 03:53