While developing Craft Commerce based website, we would apply different fileters and sorting on product listing page. Also, apply sorting based product popularity or products views. Here, I would like to mention simplest way to set product's view count in just few steps:
- Create a Number type field like “Total Views” and assign this field to product type.
- Within the product template, write this code to increment to view count whenever a product page is opened:
{# set product view count #}
{% set currentTotalViewCount = product.totalViews|default(0) %}
{% do product.setFieldValue('totalViews', currentTotalViewCount + 1) %}
{% do craft.app.getElements().saveElement(product) %}
- Now just apply order by on product listing page like:
{% set productQuery = craft.products().type('productType').orderBy('totalViews DESC') %}
That's it …