1

So I have a Commerce product template page that grabs products something like this (segment 3 is the category slug):

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

{% set product = craft.commerce.products({
    relatedTo: category,
    status: 'live',
}).first() %}

However, I need this page to 404 if the category slug isn't in a collection of categories that are chosen in a global field:

{% for category in myGlobal.liveCategories %}
    These categories, like this one {{ category.title }}, are the only categories that are allowed right now
{% endfor %}

So I want to filter

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

against my global category field:

myGlobal.liveCategories

so that only the category that gets passed to my product loop is a valid category in the global set. Here is what I'm trying to accomplish, but this code block doesn't work:

{% set category = craft.categories.slug(craft.request.getSegment(3)).first() %}

{% if category not in myGlobal.liveCategories %}
    {% redirect 404 %}
{% endif %}

I assume I have to do some twig filtering, or create arrays and combine, ...or something.

1

You can do

{% set ids = myGlobal.liveCategories.ids() %}
{% set category = craft.categories.slug(craft.request.getSegment(3)).id(ids).first() %} 
{% if category %} 
    The category is valid 
{% else %} 
    No slug found, or the category is not in the list 
{% endif %} 

Explanation: you grab all the ids from your allowed categories and search for them in your query. If a category is found it is one of the allowed categories. If not the category is another one or the there is no element with a matching slug.

  • Brilliant and does exactly what I needed. Thank you! – jrothafer Jan 21 '18 at 16:55

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.