I am using (and have used) this S.O post to create a product filter/search using multiple categories. Everything is working perfectly.
I am attempting to use the same type of logic to grab ultimately a single entry.
TL;DR: I am trying to get a single entry via 2 url segments.
I believe I am close, but what I am generating for a query isn't quite spot on as I'm always getting into my "No Products" clause.
www.mysite.com/products/toys/my-awesome-toy
{% set category = craft.request.getSegment(2) %} {# toys #}
{% set product = craft.request.getSegment(3) %} {# my-awesome-toy #}
{% set relationParam = ['and'] %}
{% if category|length %}
{% set cat = craft.categories.group('toys').slug(category).first() %}
{% set relationParam = relationParam|merge([{ targetElement: cat }]) %}
{% endif %}
cat
is outputting Toys
and my page renders all entries that belong to the Toys
category group. Perfect.
{% if product|length %}
{% set prod = craft.entries.slug(craft.request.getSegment(3)).first() %}
{% set relationParam = relationParam|merge([{ targetElement: prod }]) %}
{% endif %}
{% set entry = craft.entries.relatedTo(relationParam).first() %}
{% if entry %}
{{ entry.title }}<br>
{% else %}
<p>No products found.</p>
{% endif %}
prod
is outputting My Awesome Toy
and now I am getting my "No products found" message. I think it's because prod
is outputting My Awesome Toy
vs. my-awesome-toy
?
I realize I can get any entry via it's slug alone. I am using a dynamic route to create this page that looks like this:
products/tag/slug
I would like to get the entry strictly based on the url segments that way I can make sure my urls are valid. Meaning, I can only find "My Awesome Toy" from the "toys" category. For example:
www.mysite.com/products/toys/my-awesome-toy {# valid #}
www.mysite.com/products/food/my-awesome-toy {# invalid #}
my-awesome-toy
has an extra space behind it.{% set prod = craft.entries.slug(craft.request.getSegment(3)|trim).first() %}