1

I have 3 groups of tags that redirect to the same template. tags/index.html. All the routing and linking those tags to their group page works well.

<a href="{{ siteUrl }}taggroup/{{ tag.slug }}"

The problem I have is that when I try to enter a tag that doesn't exist on the address bar (e.g., http://sitename/taggroup/unknowntag) I get all entries displayed.

Here's my tags/index.html code:

{% if not tag %}
    {% exit 404 %}
{% endif %}

{% set tag = craft.tags.slug(tag).first %}

{% set entries = craft.entries.relatedTo(tag).order('title').limit(null) %}

 {% if entries | length %}

  {% for entry in entries %}

    <!-- Code Here -->

  {% endfor %}

  {% else %}

   <!-- No Tag Code Here -->

 {% endif %}

What Am I doing wrong? Thanks in advance.

2

That is only logical. Your tag will be null so your query is actually {% set entries = craft.entries.relatedTo(null).order('title').limit(null) %} and that results in {% set entries = craft.entries.order('title').limit(null) %} So in the end you will fetch all entries. This is what you need

{% set tag = craft.tags.slug(tag).first %}
<!-- check if the tag exists -->
{% if tag %}
    <!-- the length filter actually fetches all entries -> executes the query and caches all entries
    so you can just fetch them in the beginning. You'll gain no performance boost with that filter -->
    {% set entries = craft.entries.relatedTo(tag).order('title').limit(null).find() %}
    {% if entries %}
        {% for entry in entries %}
            <!-- code here you fetched entries -->
        {% endfor %}
    {% else %}
        <!-- you have a tag but no entries related to that tag -->
    {% endif %}
{% else %}
    <!-- you have no tag -> you won't find any entries -->
{% endif %}

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.