3

It's a pretty basic question, but for some reason all of the possible solutions do not work for me.

I tried this: https://craftcms.com/docs/relations#the-relatedTo-param And also this (which I really expected to solve my problem): https://craftcms.com/support/entries-related-to-category

I'm pretty sure I may have overlooked something, but I can't see what.

I made this:

{% set lastSeg = craft.request.lastSegment %}
{% set meubels = craft.entries.section('meubels').relatedTo(lastSeg) %}

And use this as a test:

{% for meub in meubels %}
test<br>
{{ meub.title }}<br>
{% endfor %}

According to every answer to related questions this should work, but unfortunately it returns nothing. But lastSegment does return the required string from the URL. (At least, I'm assuming this must be a string)

I made a list of categories which all seem to route just fine, no problems there.

  • Are you trying to do this from a url that is a category route? – Aaron Berkowitz Oct 15 '15 at 21:52
  • Yes, I try to get the last segment from the url and the url is analysed through a category route with a wildcard. – GeirrBenayahu Oct 16 '15 at 7:20
  • If the URL is routed form your category, you have access to a variable category in your template. category is the category model for whatever category you were routed to, so you might be able to skip the first step in my answer! – Aaron Berkowitz Oct 16 '15 at 12:53
  • Ah, indeed, you're right. This saves some lines of code. Thanks once more! :) – GeirrBenayahu Oct 17 '15 at 8:36
2

The relatedTo parameter requires one of the following as an argument: - AssetFileModel - CategoryModel - EntryModel - UserModel - TagModel - An element’s ID - An array of element objects and/or IDs

Passing in a string from the URL will not work. If you are not on a template that is the result of a category route, you need to fetch the category first.

{% set thisCategory = craft.categories.handle(lastSeg).first() %}

You can then use thisCategory as your argument in the relatedTo parameter.

{% set meubels = craft.entries.section(‘meubels’).relatedTo(thisCategory) %}
  • Thanks a lot! I was not aware of the required first line. – GeirrBenayahu Oct 16 '15 at 7:20
  • 1
    Although it first did not work as expected (it returned all entries that had any category connected to it). I changed {% set thisCategory = craft.categories.handle(lastSeg).first() %} to {% set thisCategory = craft.categories.title(lastSeg) %} and now it works! :) – GeirrBenayahu Oct 16 '15 at 7:21

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.