2

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 #}
  • Rule out one thing. See if my-awesome-toy has an extra space behind it. {% set prod = craft.entries.slug(craft.request.getSegment(3)|trim).first() %} – aran Oct 28 '15 at 22:46
1

An entry is not related to itself, but that's what you added as a filter. Use the slug parameter instead.

{% set categorySlug = craft.request.getSegment(2) %}
{% set productSlug = craft.request.getSegment(3) %}

{% set entries = craft.entries.section('products') %}

{% if categorySlug|length %}
    {% set category = craft.categories.group('toys').slug(category).first() %}
    {% if category %}
        {% set entries = entries.relatedTo({ targetElement: category }) %}
    {% endif %}
{% endif %}

{% if productSlug|length %}
    {% set entries = entries.slug(productSlug) %}
{% endif %}

{% set product = entries.first() %}
| improve this answer | |

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.