2

Is there a way I can reverse use the User Model to return an authorId based on the first/last name (John Doe)?

Basically, I'm converting the first/last to a readable URI segment (using email addresses as username and I want something more readable than an ID in the URL):

{{ entry.author.firstName|lower ~ '-' ~ entry.author.lastName|lower }}

Returns: john-doe

Then on the listing page, grabbing the URI segment, setting that back to a readable name and spliting to array.

{% set authorName = craft.request.segment(3)|replace({'-':' '})|title|split(' ') %}

Which gives me (the equivalent of):

Array
(
  [0] => John
  [1] => Doe
)

I'd like to get the author id to return all the entries from said author. I thought something along the lines of below would work:

{% set author = craft.users.firstName(authorName.0).lastName(authorName.1) %}

With the above, I get the error:

Object of class Craft\ElementCriteriaModel could not be converted to string

However, if I return {{ authorName.0 }} it returns a string.

2

Well, I was 1 minute away from solving this, so I'll post my answer.

{% set author = craft.users.firstName(authorName.0).lastName(authorName.1).first() %}

Once the author object is set, you can access the {{ author.id }}.

Allowing me to neatly return author entries:

{% set entries = craft.entries.section('news').authorId(author.id).limit('10') %}
| improve this answer | |
  • What happens when 2 or more people share the same first and last name? You'll just be grabbing the first result returned and ignoring the rest. – Brad Bell Jan 22 '15 at 5:36
  • Errrr, fair point, though it will never be the case for this particular site. Is there another way of handling it without having an email address or id in the url? – Ryan Shrum Jan 22 '15 at 14:44
  • usernames are unique. – Brad Bell Jan 22 '15 at 16:06
  • 1
    I'm using email address as username. One solution would be to have the user id as a segment for query purposes, but then have above method for human readable/SEO. i.e. /news/author/1/john-doe – Ryan Shrum Jan 22 '15 at 18:19

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.