1

Can someone tell me why I am going crazy and cannot figure this simple relatedTo issue out?

So I have a categories section called Case Studies and several categories within. I am trying to filter the results to show all entries within a specific category.

{% set entries = craft.entries.section('caseStudies').relatedTo('municipal').find() %}

won't show any results but using the ID will.

{% set entries = craft.entries.section('caseStudies').relatedTo(422).find() %}

I've tried all sorts of slugs and nothing is showing. Why can I not figure this out. someone please point out my obvious mistake...

My entry field is called 'caseStudyCategory'

1 Answer 1

4

It does not work because the function does not accept slugs. Not sure what to answer here. It only accepts objects of type Element and ids as identifier.

You can see the magic here

foreach ($elements as $element) {
if (is_numeric($element)) {
    $relElementIds[] = $element;
} else if ($element instanceof ElementInterface) {
    $relElementIds[] = $element->id;
} else if ($element instanceof ElementQueryInterface) {
    foreach ($element->ids() as $id) {
        $relElementIds[] = $id;
    }
}

These are all kind of things that the relatedTo can use/work with. If you want to get a relation by slug you have to fetch the element first.

.relatedTo(craft.categories.slug('municipal').one())
1
  • @terryupton Assuming you're in a category template, you could also just do .relatedTo(category) as well.
    – jsun
    Commented Apr 2, 2018 at 20:51

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.