We use cookies to make your viewing experience better. By accepting you consent, you agree to our Cookie policy

Accept
Improve your Craft CMS skills

How To Count Entries In A Structure In Craft CMS

10 min read
Shape April 2022 HR 28

Counting entries dynamically in Craft CMS structures provides invaluable insights for developers and content editors alike. This guide will cover simple yet powerful techniques to tally entry counts across sections, implementing filters, optimizing with caching, and leveraging the data to create smarter frontends. Whether you need to build pagination, drive conditional display logic, or generate reports, accurately counting entries in Craft unlocks a world of possibilities.

Use entryCount variable to get total entries in a section, filtered any way needed. Loop through multiple sections, summing individual entryCounts. Cache results to avoid repeated queries, with expiration rules based on update frequency. Conditionally display counts in Twig templates for pagination, filters, and more. Accurately tally entries across structures with caching for optimal performance.

Counting Entries in Craft CMS

Overview of Craft CMS

Craft CMS is a flexible, user-friendly content management system that enables you to build feature-rich websites. Its powerful content structuring capabilities allow you to organize your content elegantly.

In Craft, content is housed in 'sections' which function like content types or collections. For example, you may have a 'Blog' section, a 'Products' section, or a 'News' section. Within each section, you can have multiple 'entries' or pieces of content.

Each entry is made up of custom fields that you define. So an 'Article' entry in your Blog section could have fields like 'Title', 'Author', 'Post Body', etc. This enables you to store precisely the content you need for each entry.

With its flexible structures and custom fields, Craft provides endless possibilities for modeling your content. You can customize it to match your site's unique requirements.

Use Cases for Counting Entries

Being able to count entries in Craft CMS has numerous useful applications:

Pagination - When displaying entries, it's common to paginate results across multiple pages. To build a pagination system, you need to know the total number of entries available. Entry counts enable you to calculate pages correctly.

Conditional Display - You may want to show or hide certain UI elements based on the number of entries. For example, only showing filter/search options when there are more than 10 entries. Entry counts allow smart conditional display like this.

Search Filtering - When searching entries, it's helpful to display the number of results to the user. Entry counts make this possible, improving the search experience.

Ordering/Sorting - Allowing users to order entries by date or title relies on accurately counting entries. Entry counts facilitate advanced sorting and ordering functionality.

Statistics/Reports - You may want to generate reports on the number of entries created over time. Entry counts can provide the raw data for useful statistics and reports.

Performance Optimisation - When displaying entries, you can use entry counts to optimise database queries for faster performance. For example, batching entries into smaller groups.

Progress Tracking - In editorial workflows, entry counts enable tracking how many posts have been written versus have been published. Great for tracking progress.

Data Analysis - Counting entries in different sections/categories can reveal insights like which content types are most popular. Entry counts enable interesting data analysis.

Content Planning - When planning future content, entry counts help identify gaps or saturation in different topics. Useful for steering content planning.

Resourcing - Entry counts indicate how much existing content there is, which guides decisions on allocations of editing/production resources.

Counting entries in Craft provides tremendous utility for both site managers and end users. The entry count data powers everything from navigation design to search behaviour to content planning. It's an invaluable Yet Simple piece of metadata.

Accessing and Organizing Entries in Craft CMS

Entries in Structures and Sections

In Craft CMS, entries live within 'structures' that allow you to organize your content elegantly.

The primary structures are:

Sections - Sections function like content types or collections. For example, you may have a 'Blog' section, a 'Products' section, or a 'Events' section.

Entry Types - Within a section, you can have multiple entry types to categorize content. For example, the Blog section could contain 'Article', 'Video', 'Podcast' entry types.

Fields - Each entry type contains custom fields that enable you to tailor the content to your needs. For example, 'Title', 'Author', 'Post Body' fields for articles.

Some common structures in Craft sites include:

  • Blog Section
    • Article Entry Type
      • Title Field

      • Post Body Field

      • Author Field

  • Products Section
    • Product Entry Type
      • Title Field

      • Description Field

      • Price Field

  • Services Section
    • Service Entry Type
      • Title Field

      • Description Field

      • Icon Field

As you can see, structures provide a powerful way to organize diverse content types on a site.

Entry Types

Entry types in Craft allow you to categorize and define different content models within a section.

For example, within a Blog section, you may have:

  • Article - For longform textual blog posts

  • Video - For videoblogs and presentations

  • Podcast - For audio podcast episodes

Each entry type has its own tailored fields to match its content type.

Some other common entry types include:

  • Event - For events listings

  • Product - For product catalog entries

  • Service - For service descriptions

  • Case Study - For customer case studies

  • Team Member - For team member profiles

  • Testimonial - For client testimonials

Entry types enable you to create virtually any content structure needed. You can have multiple entry types within a section, categorising entries based on their content format and characteristics.

Working with Entries and Fields

In order to output and display entries in the frontend, you'll work with Craft's Twig templates and tags.

Some examples include:

  • {% for entry in entryQuery %} - Loop through a list of entries

  • {{ entry.title }} - Output the value of the 'Title' field

  • {% if entry.author == 'Bob' %} - Conditional based on field value

For complex entries, you may leverage relationship fields to connect entries across sections:

  • {% for product in entry.relatedProducts %} - Loop through related products

Or matrix fields to enable multi-block entry formats:

  • {% for block in entry.matrixFieldHandle %} - Loop through matrix blocks

Some key advantages of working with entries and fields:

  • Flexibility - Display any content, in any order needed

  • Consistency - Reuse fields across multiple sections/entry types

  • Logic - Build smart templates using field values

  • Relationships - Connect entries across sections as needed

  • Matrices - Construct multi-block/multi-type entries

Craft CMS provides a robust set of tools for working with entries and fields in the templates. Whether displaying titles and descriptions, or complex relationship-based queries,

Craft allows full control and flexibility.

Developers and site builders can access, organize, and output entries and fields in endless ways to create customized site designs and experiences. The modular approach enables both consistency and flexibility simultaneously.

Counting Entries in a Single Section

Using entryCount Variable

One of the simplest ways to get a count of entries in Craft is via the entryCount variable.

This variable returns the total number of live entries in a given section. For example:

{% set entryCount = craft.entries.section('blog').entryCount %}

{# Total blog entries #}

{{ entryCount }}


The entryCount is efficient because it returns just a number, avoiding any need to loop

through all the entries individually.

Some other examples of entryCount by section:

{% set articleCount = craft.entries.section('articles').entryCount %}


{# Total articles #}

{{ articleCount }}

{% set productCount = craft.entries.section('products').entryCount %}


{# Total products #}

{{ productCount }}


As shown, entryCount provides a handy way to quickly get entry totals for a specific section.

Filtering entryCount

You can also filter entryCount by parameters to get more specific counts.

For example, to count only entries of a certain entry type:

Copy code

{% set blogCount = craft.entries

.section('blog')

.type('article')

.entryCount %}

{# Total blog article entries #}

{{ blogCount }}


Other filters you could apply to entryCount:

  • By author

  • By posting date

  • By custom field value

  • By search query match

  • By status (live, pending, expired)

This enables very targeted counting. For example:

{% set newProductCount = craft.entries

.section('products')

.postDate('> 1 week ago')

.entryCount %}

{# New products in past week #}

{{ newProductCount }}

As shown, the filters allow you to tap into extremely specific slices of your content.

Displaying entryCount

A common way to display entry counts is with conditionals in your Twig templates.

For example, to show a sidebar filter only if there are more than 10 entries:

{% if blogCount > 10 %}

{% include '_filters' %}

{% endif %}

Or to conditionally switch from a list to a grid view based on entry count:

{% if productCount >= 24 %}

{% include '_grid' %}

{% else %}

{% include '_list' %}

{% endif %}

This enables all sorts of dynamic display logic tailored to the actual content volumes.

Other examples:

  • Showing pagination controls only if entryCount is more than page size

  • Hiding "No entries found" message if entryCount is greater than zero

  • Loading different sized image assets based on entryCount

In summary, the entryCount variable provides an easy way to get total counts of entries in a section, filtered any way needed. Displaying these counts in conditionals enables the creation of smart, dynamic interfaces all driven by live content data.

Counting Entries Across Multiple Sections

Summing Entry Counts

To get a total count of entries across multiple sections, you can loop through and sum each section's entryCount.

For example:

{% set totalCount = 0 %}


{% for section in ['blog', 'news', 'articles'] %}


{% set entryCount = craft.entries.section(section).entryCount %}

{% set totalCount = totalCount + entryCount %}


{% endfor %}


{{ totalCount }}


This loops through the blog, news and articles sections, gets each entryCount, and accumulates the total.

You can also filter each section differently when getting its entryCount:

{% set totalCount = 0 %}


{% set blogCount = craft.entries.section('blog').type('article').entryCount %}

{% set newsCount = craft.entries.section('news').postDate('> 1 month ago').entryCount %}

{% set articleCount = craft.entries.section('articles').level(2).entryCount %}

{% set totalCount = blogCount + newsCount + articleCount %}

{{ totalCount }}

As you can see, extensive flexibility to tailor entry counting across multiple sections.

Live Entry Counting

A common need is to get a total count of live entries only across sections.

You can do this by calling .status('live') on each section's entry query:

{% set totalLiveCount = 0 %}


{% set blogCount = craft.entries.section('blog').status('live').entryCount %}

{% set newsCount = craft.entries.section('news').status('live').entryCount %}


{% set totalLiveCount = blogCount + newsCount %}

{{ totalLiveCount }}

This ensures you only count currently published, live entries.

Entry Counting by Type

You can also sum entry counts across sections filtered by the same entry type.

For example, to total all "article" entries:


{% set sections = ['blog', 'news', 'magazine'] %}

{% set totalArticles = 0 %}


{% for section in sections %}


{% set articles = craft.entries.section(section).type('article').entryCount %}

{% set totalArticles = totalArticles + articles %}

{% endfor %}

{{ totalArticles }}

This allows getting a bird's eye view of content volumes by type.

You could even get more advanced, counting multiple types:

{% set articles = 0 %}

{% set videos = 0 %}


{% for section in sections %}


{% set articles = articles + craft.entries.section(section).type('article').entryCount %}

{% set videos = videos + craft.entries.section(section).type('video').entryCount %}

{% endfor %}

{# Display totals #}

In summary, Craft provides flexible tools for counting entries across multiple sections, with customizable filters, and the ability to sum counts in any number of ways.

Shape April 2022 HR 202
Andy Golpys
- Author

Andy has scaled multiple businesses and is a big believer in Craft CMS as a tool that benefits both Designer, Developer and Client. 

Share
Feedback
Show us some love
Email Us
We usually reply within 72 hours
Agency Directory
Submit your agency
Affiliate Partners
Let's chat