My original question here helped me figure out how to build my URL structure but now the site has introduced two categories: design and photo.

I want the "Prev" and "Next" buttons to navigate back and forth within the category of the current entry.

I know how to get the category of the current entry here:

{% for category in entry.category %}
   {{ category.title }}
{% endfor %}

...but I don't know how to put category.title into a variable to build my params. This is my best shot at the solution but it's broken and I've given up spinning on it myself :) Any help would be much appreciated.

{% set category = "craft.categories.relatedTo(entry)" %}

{% set params = craft.entries.section('projects').order('title asc').relatedTo(category) %}

{% set prevEntry = entry.getPrev(params) %}
{% set nextEntry = entry.getNext(params) %}

{% if nextEntry %}
    {% set nextEntryUrl = nextEntry.url %}
{% else %}
    {% set firstEntry = craft.entries.section('projects').first() %}
    {% set nextEntryUrl = firstEntry.url %}
{% endif %}

{% if prevEntry %}
    {% set prevEntryUrl = prevEntry.url %}
{% else %}
    {% set lastEntry = craft.entries.section('projects').last() %}
    {% set prevEntryUrl = lastEntry.url %}
{% endif %}

A category is an element. So is an entry, and an asset, and a tag, and user. When you relate one element with another you get returned an ElementCriteriaModel in the template. So you need to use its methods to actually get the element data. In this case first().

So if you know for sure that you only have (and care about) one category in an entry, then you can try this for your params.

{% set params = craft.entries.section('projects').order('title asc').relatedTo(entry.category.first()) %}

You could also set category way up at the top of the template if you know you'll use it multiple times in the template. That way you are only making one database query.

{# At the top of the template #}
{% set category = entry.category.first() %}

{# Somewhat lower to display the category #}
{{ category.title }}

{# even lower to pull the other entries. #}
{% set params = craft.entries.section('projects').order('title asc').relatedTo(category) %}
|improve this answer|||||
  • Thanks Bryan! Makes sense now. The only issue is that while the "Prev" button works consistently, the "Next" button goes through all the entries, in order, of the "photo" category (for instance), then goes onto the entries of the other category "design" and loops them infinitely. I can't seem to make sense of it. – Jeremy P. Beasley Jan 5 '16 at 2:20

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.