skip to Main Content

I don’t know how to get the total count of my products in shopify graphql. I need to get the total count of my products in shopify because I am creating a pagination with numbers. As of now I created cursor-based pagination which is the next and previous buttons but I want to add numbers of pages.

I tried to remove the variable $numberProduct, I am using this to fetch only of number of products (9) per page and now I directly put the first: 100 in my query and the numbers or array of pages is showing but all of my products is showing in my product page/blade view because I declare it in my query which is the 100.

This is my logic on how to get the numbers of pages:
// Calculate total number of products
$totalProducts = count($data[‘data’][‘products’][‘edges’]);

            // Calculate total number of pages
            $totalPages = ceil((int)$products / $numProducts);

            // Generate an array of page numbers
            $pageNumbers = range(1, $totalPages);

Output: 1 number of pages

This is where I try to remove the variable $numberProduct and declare directly to my query first: 100:
// Calculate total number of products
$totalProducts = count($data[‘data’][‘products’][‘edges’]);

            // Calculate total number of pages
            $totalPages = ceil((int)$totalProducts / 9);

            // Generate an array of page numbers
            $pageNumbers = range(1, $totalPages); 

Output: 12345678 number of pages which is correct

2

Answers


  1. You cheat and skip the GQL and just ask the products endpoint for the count. Same as asking the RestAPI for the count. Instant and easy. There is no analog in GQL for that. GQL works off of cursors, arguably the much faster way of paging through products, but there is no totalCount with GQL.

    Login or Signup to reply.
  2. This is just an idea, I’m not sure if it will work:

    $api = ShopifyApp::api();
    // Define the query.
    $query = 
    '{
       shop
       {
          products(first: 1)
          {
             totalCount
          }
       }
    }';
    $response = $api->graph(GraphqlEnum::ADMIN_API, new GraphqlValue($query));
    // Total count of products.
    $totalCount = $response['data']['shop']['products']['totalCount'];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search