1

I have come up with the following code to group entries by categories;

{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .orderBy('price asc')
%}

{% set hotTubsCats = craft.categories()
  .group('newHotTubBrands')
  .relatedTo(hotTubs)
%}

{% block content %}

  {# Loop the categories #}
  {% for category in hotTubsCats.all() %}

    {{ category.title }}

    {# Get and loop through entries related to this cat #}
    {% set hotTubs = craft.entries.relatedTo(category) %}
    {% for entry in hotTubs.all() %}
      {% include '_includes/blocks/related-tub-new' %}
    {% endfor %}

  {% endfor %}

{% endblock %}

However, I wanted to check if this is the most efficient approach or if this could be improved upon?

4

One improvement I think could be made is to fetch only the ID's of your hotTubs entries at the start of your code. You're only using this to get the related categories and fetching ID's is faster than fetching the actual elements. The relatedTo parameter works perfectly with ID's. So that could speed up things. You can drop the orderBy parameter also as this doesn't have any effect there.

{% set hotTubs = craft.entries()
  .section('newHotTubs')
  .ids()
%}

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.