Filtering by page date and taxonomy value

I have a taxonomy which includes this value for “readstate”. I’m trying to display a list of the most recent five pages by “date” value which also have a “readstate” of “read”. This is the code I’m using:

<h2>recently finished</h2>
<ul>
{% set sorted_pages = section.pages | sort(attribute="date", reverse=true) %}
{% set counter = 0 %}

{% for page in sorted_pages %}
  {% if page.taxonomies.readstate and page.taxonomies.readstate[0] == "read" and counter < 5 %}
    <p><li>
      {{ page.taxonomies.authorname[0] | default(value="") }}.
      ({{ page.taxonomies.pubyear[0] | default(value="") }}).
      <a href="{{ page.permalink | safe }}"><i>{{ page.title }}</i></a>.
      <br>
      {% if page.taxonomies.rating and page.taxonomies.rating | length > 0 %}
        <sub>rated {{ page.taxonomies.rating[0] }}/5</sub>
        <br>
      {% else %}
        <sub>unrated</sub>
        <br>
      {% endif %}
    </li></p>
    {% set counter = counter + 1 %}
  {% endif %}
  {% if counter >= 5 %}
    {% break %}
  {% endif %}
{% endfor %}
</ul>

… for some reason, this is displaying basically everything with a readstate of “read”. Any ideas how I can limit the output to the five most recent ones?

Thanks!

Change that to

{% set_global counter = counter + 1 %}

The normal set is tied to the loop so it was basically was never going above counter + 1

Indeed. That totally fixed it. Thanks a lot!