1

I am trying to return entries that relate to a series of categories.

For example, I am trying to return clothing, in this example, I want to return all entries related to (flannel or denim) and (blue or red) in the products channel.

Flannel, denim, blue and red are all apart of the same category group called: filters, and the category field handle is productFilters

I was trying to return all those entries but it returns 0 entries, any help is appreciated. I know I can do this probably using the craft cms element query in the template but I need to do this in a plugin.

$color_categories = craft()->elements->getCriteria(ElementType::Category, [
    'slug'  => ['blue', 'red'],
    'group' => 'filters'
])->find();

$fabric_categories = craft()->elements->getCriteria(ElementType::Category, [
    'slug'  => ['denim', 'flannel'],
    'group' => 'filters'
])->find();

$entries = craft()->elements->getCriteria(ElementType::Entry, [
    'section'           => 'products',
    'relatedTo'         => ['and', $fabric_categories, $color_categories],
]);

return $entries;
  • Just to help narrow down the potential issues— $color_categories and $fabric_categories both contain the expected results? And, in your Category group, are any of the expected results nested under one another? – August Miller Feb 3 at 16:15
  • I figured out the issue, I needed to search all entries related to the fabric categories, and other the entries related to the color categories, getting the id's all those two sets of results, do an array intersect on them, returning all the id's of entries that had (denim or flannel) and (blue or red) – Brad Feb 6 at 0:40
1

Aren't you missing the ->find() on the last bit?

$entries = craft()->elements->getCriteria(ElementType::Entry, [
    'section'           => 'products',
    'relatedTo'         => ['and', $fabric_categories, $color_categories],
])->find();
return $entries;

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.