Preserve existing query parameter while filtering

Hello,

I’m implemented storefront filtering like in the documentation here:
https://shopify.dev/docs/themes/navigation-search/filtering/storefront-filtering/support-storefront-filtering#collection-filter-display

and after that I also implemented sorting like this:

HTML:

<select
    class="all-products__filters__sort"
    id="sort-by"
>
    {% assign sort_by = collection.sort_by | default: collection.default_sort_by %}
    {% for option in collection.sort_options %}
        <option value="{{ option.value }}"
            {% if option.value == sort_by %}
                selected="selected"
            {% endif %}
        >
            {{ option.name }}
        </option>
    {% endfor %}
</select>

JS:

<script>
  Shopify.queryParams = {};

  // Preserve existing query parameters
  if (location.search.length) {
    var params = location.search.substr(1).split('&');
    console.log(params);

    for (var i = 0; i < params.length; i++) {
      var keyValue = params[i].split('=');

      if (keyValue.length) {
        Shopify.queryParams[decodeURIComponent(keyValue[0])] =
          decodeURIComponent(keyValue[1]);
      }
    }
  }

  // Update sort_by query parameter on select change
  document.querySelector('#sort-by').addEventListener('change', function (e) {
    var value = e.target.value;

    Shopify.queryParams.sort_by = value;
    location.search = new URLSearchParams(Shopify.queryParams).toString();
  });
</script>

and when all of this is implemented, apply some sorting and ofter adding filter, sort query parameter is deleted because of new filter.

Interesting is when i add filter first and then add sort everything is working as expected, but other way around, filters always reset all query parameters… Does anybody know how to solve this issue?

One possible solution could be to modify the JavaScript code you’re using for sorting to check for existing query parameters before updating the sort_by parameter. Here’s an example of how you might modify the code:

// Update sort_by query parameter on select change
document.querySelector('#sort-by').addEventListener('change', function (e) {
  var value = e.target.value;

  // Check for existing query parameters
  var params = new URLSearchParams(location.search);
  if (params.has('page')) {
    params.delete('page');
  }

  if (params.has('q')) {
    params.delete('q');
  }

  // Update sort_by parameter
  params.set('sort_by', value);

  // Update URL with new query parameters
  var newUrl = location.protocol + '//' + location.host + location.pathname + '?' + params.toString();
  window.location.href = newUrl;
});

This code checks for existing query parameters and removes any that could interfere with the sorting. It then updates the sort_by parameter and redirects the page to the updated URL.

If you read last part of my message, you can see that sorting was working fine, problem is with filtering