I have two category groups: Cars
and Colors
My Cars
category looks like this:
Cars
Sports Cars
Corvette
Lamborghini
Porche
My Colors
category looks like this:
Colors
Red
Black
White
I have two drop-down menus; one to choose the car, the other to choose the color.
I can choose the car, or the color just fine. My url's look like this:
mysite.com/cars/corvette/
- or -
mysite.com/cars/red/
It's when I need to relate both categories. Since my two category groups have different levels, I'm not sure how to get the parent group of Colors
from red
. Which is what I think I need in order for the relatedTo
to work properly.
For example, a url might look like this:
mysite.com/cars/corvette/ {# no problem #}
- or -
mysite.com/cars/red/ {# no problem #}
I'm able to get to the categories on my template:
{#
# Get the primary category GROUP via url segment.
# Example: Cars
#
#}
{% set primaryCategoryGroup = craft.categories.slug(craft.request.getSegment(2)).first() %}
{#
# Get the primary CATEGORY via url segment.
# Ex: Corvette or Red
#}
{% set primaryCategory = craft.categories.slug(craft.request.getSegment(3)).first() %}
Then I check if I need to compare both relationships:
{% if craft.request.getSegment(4)|length %}
{% set secondaryCategorySlug = craft.categories.slug(craft.request.getSegment(4)) %}
{% set secondaryCategory = craft.categories.slug(craft.request.getSegment(4)).first() %}
{{ secondaryCategory.title }} {# Red or Corvette #}
{{ primaryCategory }} {# Red or Corvette #}
{# Begin the fail #}
{% set entries = craft.entries.section('mySection').relatedTo('and',
{ sourceElement: secondaryCategory, field:'title' },
{ targetElement: primaryCategory }
) %}
{% else %}
{# Only get single relationship. #}
{% set entries = craft.entries.relatedTo(primaryCategory) %}
{% endif %}