0

I'm trying to wrap my head around Pagination in Craft. I have a template that outputs a list of products based on the Category that is passed to it from this thread:

{# Fetch the entries related to auto-injected category variable #}
{% set entries = craft.entries()
    .section('mySection')
    .relatedTo(category)
    .all()%}

{% for entry in entries %}
    <p><a href="{{ entry.url }}">{{entry.title}}</a></p>
{% endfor %}

It works great, but I need to paginate it. I'm new to Craft so I'm sure I'm missing something simple, but all the examples I've seen, plus the docs, show how to paginate based on all the entries in a section, but that's doesn't work for me here. Also, the examples seem to conflict with my code, in so far as they are using 'set entries' to get the pagination working, but I'm using it already to get every item from a category. As I said, newbie here so I'm sure I'm missing something simple; any help appreciated.

I'm also hoping I can generate a numeric pagination, but at the moment I'd settle for understanding how to get the basics working in my category example.

1

You're not far away by combining what you already have with the example in the docs! You just need to pass in the category (.relatedTo(category)) and number of entries (.limit(10)) to show on each page.

{% set query = craft.entries()
    .section('mySection')
    .relatedTo(category)
    .limit(10)
%}

{% paginate query as pageInfo, pageEntries %}

{% for entry in pageEntries %}
     <p><a href="{{ entry.url }}">{{entry.title}}</a></p>
{% endfor %}

{% if pageInfo.prevUrl %}<a href="{{ pageInfo.prevUrl }}">Previous Page</a>{% endif %}
{% if pageInfo.nextUrl %}<a href="{{ pageInfo.nextUrl }}">Next Page</a>{% endif %}
4
  • Thanks, but that doesn't work for me. It just limits the number of results returned from the Categories. In other words that .limit(10) only gives me ten results. I tried changing it to every thing from 1 to 25 and it always just limits what is returned to that limit number (total, not limited per page). What I need is every item, even if it's 200 of them, and then paginate that group to 20 per page, etc. Jan 19 at 18:25
  • Never mind, it is working now. I retried it by copy and paste and got it working (probably a typo on my end). Thanks for the help! Jan 19 at 18:43
  • Glad to hear you got it working!
    – tommysvr
    Jan 19 at 22:29
  • It works great, except it gives a Deprecation warning in the Admin panel. Apparently limit() is deprecated and you have to use all() now, but I don't understand how that would work with pagination in my case. It basically breaks this solution. Jan 21 at 20:10

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.