How to Get URL parameters in Shopify Frontend

get url parameters in liquid
get url parameters in liquid

One of our customers asks for customizing the Shopify Collection page for them, their requirement is very simple, just wants to keep one or two specified products always showing on the top whenever user change sort by conditions.

Basically there are two ways to do this:

First one:

  1. append a special parameter to the collection page URL.
  2. check to see if the specified URL parameter existing or not.
  3. if existing then get the specified product data from Shopify Store.
  4. insert the specified product into the collection product list at the head.

Second one:

  1. in the Shopify Collection template file loop all the collecion.products to get the specified top two products.
  2. remove original top two products from the collection product list.
  3. insert these two products at the top of the collection product list.

in this article we will focus on first method and how to get URL parameters in the Shopify frontend.

In order to implement this feature, we need to use JavaScript URL and URLSearchParams objects. with URL() object to get a URL object and with get() function of URLSearchParams object to get the parameter which we want.

Example codes as below:

(function($){
    $(document).ready(function(e){
      var url = new URL(location.href);
      var params = new URLSearchParams(url.search);
      var show_top_flag = params.get('show_top');
      if ( show_top_flag != null ) {  
          // show top two products logic here
          // ... 
      }
});
})(jQuery);
Please follow and like us:

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *