1

Hey I am trying to get 4 entries, but only want 4 that have a body length > 100.

How would I accomplish this?

{% for entry in craft.entries.section('artists').order('RAND()').limit(4) %}
  // only display 4 entries with entry.body|length > 100
{% endfor %}

Thanks!

3

I highly recommend to use the fantastic Preparse plugin to save to length of your body text in a hidden field.

Create and add a new "bodyLength" Preparse field to your "Artists" entry type. Use this Twig code in the field settings:

{{ entry.body|length }}

To update all existing entries, re-save them by going into Settings → Sections → Artists and click Save. You can now simply set up a criteria model to query for entries with a body length greater than 100 like so:

{% set entries = craft.entries.section('artists').bodyLength('> 100') %}
3

You could do something like this:

{# Grab all entries with a body > 100 %}
{% for entry in craft.entries.section('artists').order('RAND()').find() if entry.body|length > 100 %}

{# Limit output to the first 4 #}
{% if loop.index1 <= 4 %}
        {{ entry.id }}'s body field has a length greater than 100!<br />
    {% endif %}
{% endfor %}

Keep in mind that if entry.body is a Rich Text field than any HTML markup (<p>, <span>, etc.) will be included in that length count as well.

Twig doesn't have a break or continue tag natively, but if you install the MN Break and Continue plugin, you can make it a bit more efficient:

{# Grab all entries with a body > 100 %}
{% for entry in craft.entries.section('artists').order('RAND()').find() if entry.body|length > 100 %}
    {% if loop.index1 > 4 %}
        {% break %}
    {% endif %}

    {{ entry.id }}'s body field has a length greater than 100!<br />
{% endfor %}
  • Thanks for this Brad. using this code runs through the 4 entries and only displaying the ones that have body|length > 100. So sometime this will only display two entries since the other two has body|length < 100. What I am trying to achieve is to always show 4 entries. – Kenyon Kowal Oct 6 '15 at 21:32
  • Ahh, updated answer. – Brad Bell Oct 6 '15 at 21:45

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.