Including two category slugs in entries’ URLs I have a section with two Categories fields, and I would like the entries’ URLs to include the slugs of the categories selected in each of those fields.

The Category Groups are:


mySection


Employees
Employers
Executives

myCategory


Vitality
Health
Safety
Career



So an entry that has “Employees” selected in the first Categories field, ad “Health” selected in the second Categories field should end up with the URL:

mywebsite.nl/employees/health/entrypage


How do I do this?
Set your section’s Entry URL Format to this:

{mySection.first.slug}/{myCategory.first.slug}/{slug}


mySection.first and myCategory.first will give you the first-selected category within those respective fields. Adding .slug after that will give you the slug of those categories.

If either of those category groups can have nested categories, you may want to change .first to .last, so the last-selected category’s slug makes it into the URL rather than the first one.

Category URLs

If you would like to make category URLs like this:

mywebsite.nl/employees/health


you will need to create a new Route in Settings → Routes, with the following URL pattern:



and point the route to whatever template you want to load when these URLs are matched.

Then from your template, you can fetch the actual category models like this:

{% set mySection = craft.categories({
    group: 'mySection',
    slug: matches[1]
}).first() %}

{% set myCategory = craft.categories({
    group: 'myCategory',
    slug: matches[2]
}).first() %}

{# Make sure the URL contained valid slugs #}
{% if not mySection or not myCategory) %}
    {% exit 404 %}
{% endif %}


From there you can do whatever you want with them. For example, you can display every entry that is related to both of them:

{% set entries = craft.entries({
    relatedTo: ['and', {targetElement: mySection}, {targetElement: myCategory}]
}) %}

{% for entry in entries %}
    ...
{% endfor %}


You can repeat all of those steps to do a similar thing for URLs that just have one category in them as well (just omit the second route token, and ignore all the myCategory stuff in the example code).