Ad

How To Display Different Content IF All Of The Search.results Do Not Have Item.featured_image In Shopify Theme's Search.liquid

- 1 answer

I began working with a company that already had quite a complex theme built and live. On their collection pages and search page, the products that don't have a featured image don't get displayed. So when searching if all of the results are items that don't have featured images, all there is now is a blank space where products would be.

I'm wanting to know if it is possible in the search.liquid file to check if all the search.results are missing an item.featured_image, if that's true, then skip showing the results and display a message stating there's no results.

A stripped down example of the code now is as follows:

{% if search.performed %}
{% paginate search.results by 60 %}

{% if search.results == empty %}
<div class="row">
  <h2>Sorry! No Search Results</h2>
  <p>Your search for <strong>"{{ search.terms }}"</strong> didn't
 return any results.</p>
</div>

{% else %}

<div class="row">
  <h1>Search Results</h1>
  <p>{{ search.results_count }} Products match your search.</p>
  {% include 'pagination' %}
</div>


{% for item in search.results %}
  {% if item.featured_image == blank %}
    {% continue %}
  {% endif %}

  // looped code for each item with featured image.

{% endfor %}

{% endif %}

{% endpaginate %}

{% endif %}

Any help would be greatly appreciated!

----EDIT----

As HymnZ led me to find, simply creating a for loop to count the items.featured_image == blank and checking if that count matches search.results_count does the trick.

Replacing {% if search.results == empty %}, which determines if the No Results text will display, with the code below solves the problem.

{% assign items_blank = 0 %}
{% for item in search.results %}
  {% if item.featured_image == blank %}
    {% assign items_blank = items_blank | plus: 1 %}
  {% endif %}
{% endfor %}

{% if search.results == empty or items_blank == search.results_count %}
Ad

Answer

Replace the line {% if search.results == empty %} with the following code

{% assign items_blank = 0 %}
{% for item in search.results %}
  {% if item.featured_image == blank %}
  {% assign items_blank = items_blank | plus: 1 %}
  {% endif %}
{% endfor %}

{% if search.results == empty or items_blank == search.results_count %}
Ad
source: stackoverflow.com
Ad