9

I'm returning the username as the second segment /blog/username and then setting the username var to craft.request.segment(2).

I'm looking to list a group of entries by that author (username). I've tried:

{% set blogPosts = craft.entries.section('blog').relatedTo(username) %}

I've also tried this:

{% set blogPosts = craft.entries.section('blog').relatedTo({ targetElement: username, field: 'author' })%}

Anyone have a way to list through entries related by author?

8

Try this:

{# First, grab the username from the URI #}
{% set username = craft.request.segment(2) %}

{# Then, grab the user based on the username %}
{% set user = craft.users.username(username).first() %}

{# Make sure we actually found a user #}
{% if user %}
    {% set blogPosts = craft.entries.section('blog').authorId(user.id).find() %}

    Found: {{ blogPosts|length }} blog posts.
{% endif %}
  • Thanks for the reply Brad. The first part is working with a bit of modification {% set user = craft.users.username(craft.request.segment(2)).first() %}; {{ user }} returns the correct value, however when added to .relatedTo() it doesn't return any results (should in this case have 2 entries returned). – Ryan Shrum Jul 3 '14 at 16:32
  • Try your 2nd example, then, with a slight modification to field {% set blogPosts = craft.entries.section('blog').relatedTo({ targetElement: user, field: 'authorId' })%} – Brad Bell Jul 3 '14 at 16:35
  • That didn't work either. I tried a few different iterations of the same line: { targetElement: user, field: authorId } { targetElement: user.id, field: authorId } { targetElement: userd, field: 'authorId' } { targetElement: user.id, field: 'authorId' } You get the idea. – Ryan Shrum Jul 3 '14 at 16:53
  • Check the latest edit. Actually tested this one. :) – Brad Bell Jul 3 '14 at 17:08
  • Now we're in business! Thanks for that. I guess I'll have to install the Happy Brad plugin now... -sigh- – Ryan Shrum Jul 3 '14 at 17:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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