1

I have a blog, and in the sidebar I have listed all tags in use. I would like to link each tag - when you click it I want to link to a page that lists all the blog entries which have that tag applied to them. Cant find this in the docs.. would someone mind helping? Here is my code so far:

<div class="tagblock">
    {% set entries = craft.entries.section('blog').limit(null) %}
         {% for tag in craft.tags %}
           <div class="tag"><a href="{{ url('blog-page/'~tag.id) }}">{{ tag.title }}</a></div>
    {% endfor %}
</div>

MY RESULTS: This code is linking to for example mysite.com/blog-page/88 - and giving me a page not found. I have a template blog-page and the path is correct as the page loads if you remove the tag-id off the end.

Thanks

1 Answer 1

4

You don't have a setting in Craft to make Tags have their own pages automatically. So what you have to do instead, is to set up a dynamic route in Settings → Routes. Create a new route which routes these URIs: blog/tags/[slug] (drag the slug token into the URI field) to a template blog/_tags.html.

In your blog/_tags.html template you will now have a slug variable available, but you still need to query for the tag model / entry models.

{% set tag = craft.tags.slug(slug).first() %}
{% if not tag %}{% exit 404 %}{% endif %}

{% set entries = craft.entries.section('blog').relatedTo(tag).limit(null) %}

<h2>{{ tag.title }}</h2>

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

I'd also modify the tag listing to only show tags that are actually related to an entry, and use the tags' (undocumented) slug property for SEO purposes:

{% set entries = craft.entries.section('blog').limit(null) %}
{% set tags = craft.tags.relatedTo(entries).limit(null) %}

{% for tag in tags %}
    <a href="{{ url('blog/tags/'~tag.slug) }}">{{ tag.title }}</a>
{% endfor %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.