Have you ever wondered how to automatically count the number of CMS items in a CMS collection and display it on the page? This can for instance be useful if you have one (or several) collection(s) of blog articles and want to show your visitors how many articles are available for him to read. This could be applied to anything like recipes, news articles, tutorials etc. This functionality can't be achieved without custom code, and I'll show you how to do this here.
- Pull a new CMS collection list element onto your page and connect it to a CMS collection. Give the CMS collection item the class name of .my-counter
- Create a new text item (this could be a headline, paragraph or text block, text link etc.) that you'd like to display your counter number in. Give this text element a class name of .mycounter-hack
- Access your "Before </body> tag" area in the custom code section in your page settings (not site settings!) and copy the following code in:
const mycounter = $('.my-counter').length;$('.mycounter-hack').text(mycounter);});
This code specifies that all classes with the class name of .my-counter will be counted and output inside the element with the class name .mycounter-hack
- You can add additional CMS collections to the page and as needed and change any of the class names to your liking. Just remember to hide the CMS collections on the page when you're done, so they are not visible to your site visitors. Also, one word of caution: if you are planning to use CMS collections that contain hundreds of entries, your site performance might suffer, so you are better off only using this hack if your collection contains a limited amount of items only.
This article was inspired by Finsweet's tutorial which you can find here.