How To Paginate Shopify Products with Product REST API

  Shopify

So you have finally learned how to display products using Shopify Product REST API. However, you have a bit of a problem, you want to display products with pagination and the only thing you think you can do is to create an array of products and display them depending on their keys.

Believe it or not, it’s not actually a bad idea but offers a TON of work.

Shopify Product API (version 2019-07 and beyond) provides a link header that you can use for requesting paginated REST Admin API endpoints and that’s what we’re going to learn today.

Keep in mind that before proceeding, you must know already how to use Shopify API or you have created a Shopify app using our Shopify app development tutorial.

If in case this is your first time, we highly suggest you read our tutorial below.

Read more: How To Create Shopify Apps from Scratch

Getting Started

Before you can create pagination, it’s important to understand that this will only work for API version 2019-07 and beyond. So if you’re using an old version of the API, then we highly recommend you to go to your app settings and update your API version.

Shopify Webhooks API versioning latest

Another important thing is to understand how the product API works. By default, you can return up to 50 products per page but you can also maximize the number up to 250 products.

Each page will provide you a set of links in the header that you can use to go to the next or previous set of items.

To properly explain this… Let’s say we have 200 products, and we want to display 10 products per page.

If we are on the very first page of our products, the API will give us just one link in the header, for us to be able to go to the next page.

If we are on the second page, the API will give us two links in the header, one for the previous page and one for the next page.

And so on, and so forth.

Displaying Products

If you have been following us for a while, then you probably know already how to display Shopify products using PHP and Shopify API.

Let’s say we have the following code:

<?php require_once("inc/functions.php"); require_once("inc/connect.php"); $requests = $_GET; $hmac = $_GET['hmac']; $serializeArray = serialize($requests); $requests = array_diff_key($requests, array( 'hmac' => '' )); ksort($requests); $sql = "SELECT * FROM example_table WHERE store_url='" . $requests['shop'] . "' LIMIT 1"; $result = mysqli_query( $conn, $sql ); $row = mysqli_fetch_assoc($result); $token = $row['access_token']; $shop = "weeklyhow"; $products = shopify_call($token, $shop, "/admin/api/2019-10/products.json", array(), 'GET'); $products = json_decode($products['response'], JSON_PRETTY_PRINT); ?> <!DOCTYPE html> <html> <head> <title>Shopify Example App</title> </head> <body> <div> <ul id="product-list"> <?php foreach($products as $product){ foreach($product as $key => $value){ echo '<li>' . $value['title'] . '</li>'; } } ?> </ul> </div> </body> </html>

If you noticed, we are using MySQL database to get our access token so if you’re not sure how to connect your Shopify app to your database. We highly recommend you follow our previous tutorials.

The code above will simply display all the products you have in your store like below.

Displaying all products with Shopify Product API

In total, we have 27 products.

Now, the next thing that we’re going to do is to make limitations for our API. Let’s say we just want to display 5 products per page.

To do that, we need to create an array where we indicate how many items we want to display using the parameter limit.

$array = array( 'limit' => 5 ); $products = shopify_call($token, $shop, "/admin/api/2019-10/products.json", $array, 'GET'); $products = json_decode($products['response'], JSON_PRETTY_PRINT);
Shopify Product API limit parameter

Awesome! Now we’re just displaying the first 5 products.

Previous & Next Buttons

Now that we have successfully displayed and limit our products. Let’s create the buttons that we’re going to use to navigate to the next page (…and also the previous page of course).

Just underneath your unordered list element, add the following code.

<div> <button type="button" data-info="" data-rel="previous" data-store="<?php echo $row['store_url']; ?>">Previous</button> | <button type="button" data-info="" data-rel="next" data-store="<?php echo $row['store_url']; ?>">Next</button> </div>
Shopify Product Pagination API previous and next buttons

Awesome!

Updating functions.php

If you’re using the same files that we use for developing Shopify apps, then you’ll most likely encounter the very same bug that we experience whenever we use shopify_call() function.

If you use the said function just for the sake of returning Shopify’s response, then you might think that there’s no problem at all.

However, when you use the function to get headers, specifically for making pagination. You will notice that there’s something wrong/missing and that is the link header.

Shopify API getting the link in the header for pagination

The main reason why that’s happening because of the ‘colons’ in the header.

The functions.php file is simply using the explode() function to create an array for the header. Then loop through each key in the array, and explode once again with the help of colon this time. That’s also where the issue starts to develop.

Since URLs have their own colon (https://), the function explode will obviously malfunction.

So with all that being said, let’s update our functions.php.

Look for the following lines of code:

foreach($header_data as $part) { $h = explode(":", $part); $headers[trim($h[0])] = trim($h[1]); }

and change it to…

foreach($header_data as $part) { $h = explode(":", $part, 2); $headers[trim($h[0])] = trim($h[1]); }

The file functions.php is located in inc folder.

Very simple, we only have to add a limit to our explode function. If the explode function hits the first separator, it should end the process.

Now let’s go back to our index file and update the following code:

$array = array( 'limit' => 5 ); $products = shopify_call($token, $shop, "/admin/api/2019-10/products.json", $array, 'GET'); $products = json_decode($products['response'], JSON_PRETTY_PRINT);

to…

$array = array( 'limit' => 5 ); $products = shopify_call($token, $shop, "/admin/api/2019-10/products.json", $array, 'GET'); $headers = $products['headers']; $products = json_decode($products['response'], JSON_PRETTY_PRINT); foreach ($headers as $key => $value) { echo '<div>[' . $key . '] =>' . $value . '</div>'; }

In the code above, we simply created a new variable and retrieved the headers.

And then underneath the $products variable, we check each value inside the $headers variable using foreach function

You should have the following output.

Shopify header response for link and product pagination

If you look closely, you can clearly see that the link key only a value of ; rel="next".

That’s because of the rest of its value is being converted to an HTML instead of a string.

So if you go to your inspector, you will see that everything was enclosed with the <https></https> tag.

Shopify Header API link header being HTML

To solve that issue, we need to create our own function to extract the string between the angle brackets.

So open your functions.php file once again and just underneath your shopify_call() function, add the following code.

//shopify_call() { ... } <--- make sure you add the code outside this function function str_btwn($string, $start, $end){ $string = ' ' . $string; $ini = strpos($string, $start); if ($ini == 0) return ''; $ini += strlen($start); $len = strpos($string, $end, $ini) - $ini; return substr($string, $ini, $len); }

Going back to index.php file. And just underneath the foreach() function, add the following code.

$nextPageURL = str_btwn($headers['link'], '<', '>'); $nextPageURLparam = parse_url($nextPageURL); parse_str($nextPageURLparam['query'], $value); $page_info = $value['page_info'];

Next, we’ll update our Next button’s data-info attribute from.

<button type="button" data-info="" data-rel="next" data-store="<?php echo $row['store_url']; ?>">Next</button>

to…

<button type="button" data-info="<?php echo $page_info; ?>" data-rel="next" data-store="<?php echo $row['store_url']; ?>">Next</button>

Scripting Shopify Pagination with AJAX

We basically got everything we need to display our products and pagination. Now let’s work with AJAX so we can retrieve the next and previous products.

Just before your body closing tag, add the following code.

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script> $('button').on('click', function(e) { var data_info = $(this).attr('data-info'); var data_rel = $(this).attr('data-rel'); var data_store = $(this).attr('data-store'); $.ajax({ type: "GET", url: "pagination.php", data: { page_info: data_info, rel: data_rel, url: data_store }, dataType: "json", success: function(response){ if( response['prev'] != '' ) { $('button[data-rel="previous"]').attr('data-info', response['prev']); } if( response['next'] != '' ) { $('button[data-rel="next"]').attr('data-info', response['next']); } if( response['html'] != '' ) { $('#product-list').html(response['html']); } } }); }); </script>

Don’t forget to save your files.

The Pagination Script

Now that we have finally programmed our index file, let’s create a new PHP script for our AJAX. Of course, we’ll call it pagination.php.

<?php require_once("inc/functions.php"); require_once("inc/connect.php"); //Retrieve all the data values that we need $page_info = $_GET['page_info']; $rel = $_GET['rel']; $store_url = $_GET['url']; $sql = "SELECT * FROM example_table WHERE store_url='" . $store_url . "' LIMIT 1"; $result = mysqli_query( $conn, $sql ); $row = mysqli_fetch_assoc($result); $token = $row['access_token']; $shop = "weeklyhow";

First of all, we need to get everything that we need such as our access token, our shop subdomain, and the data values that we passed through AJAX.

Next, we’ll create the API. So just underneath the code, add the following:

//Create an array for the API $array = array( 'limit' => 5, 'page_info' => $page_info, 'rel' => $rel ); $products = shopify_call($token, $shop, "/admin/api/2019-10/products.json", $array, 'GET');

Next, we’ll create everything we need for our headers, check if the link header contains two page_infos, otherwise retrieve the default value.

//Get the headers $headers = $products['headers']; //Create an array for link header $link_array = array(); //Check if there's more than one links / page infos. Otherwise, get the one and only link provided if( strpos( $headers['link'], ',' ) !== false ) { $link_array = explode(',', $headers['link'] ); } else { $link = $headers['link']; }

Next, we’ll create another set of variables and check if the $link_array count is greater than one. If it is, then we take the two page_infos from each link array. Otherwise, just get what’s provided.

//Create variables for the new page infos $prev_link = ''; $next_link = ''; //Check if the $link_array variable's size is more than one if( sizeof( $link_array ) > 1 ) { $prev_link = $link_array[0]; $prev_link = str_btwn($prev_link, '<', '>'); $param = parse_url($prev_link); parse_str($param['query'], $prev_link); $next_link = $link_array[1]; $next_link = str_btwn($next_link, '<', '>'); $param = parse_url($next_link); parse_str($param['query'], $next_link); } else { $prev_link = $link; $prev_link = str_btwn($prev_link, '<', '>'); $param = parse_url($prev_link); parse_str($param['query'], $prev_link); $next_link = $link; $next_link = str_btwn($next_link, '<', '>'); $param = parse_url($next_link); parse_str($param['query'], $next_link); }

And last but not least, we’ll create the variable for our frontend to display the next set of products.

//Create and loop through the next or previous products $html = ''; $products = json_decode($products['response'], JSON_PRETTY_PRINT); foreach($products as $product) { foreach($product as $key => $value) { $html .= '<li>' . $value['title'] . '</li>'; } }

Seriously though, this is the last…

Let’s encode everything into JSON and pass it back to AJAX.

//Then we return the values back to ajax echo json_encode( array( 'prev' => $prev_link['page_info'], 'next' => $next_link['page_info'], 'html' => $html, 'token' => $token ) );

Save all your files and you should have the following output.

Conclusion

If you have reached this part then good job! You have successfully learned how to create pagination for your Product API. Obviously, there are plenty of other ways to do this but this tutorial is just to give you an idea that it is possible to make paginations for products.

If you have concerns or questions, don’t hesitate to let us know in the comments below!

React to this topic
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments