How to Display Related Products Using WooCommerce REST API

When it comes to online stores it is obvious to show related products on the single product detail page. It helps your customers to show similar products they maybe want to buy. It also increases user engagements on your website. As more time customers spend on your store, there are more chances they would buy your products. In this article, I show you how to show related products using the WooCommerce REST API.

In this tutorial, I will fetch all products related to the current product and then display it. I also link each product to its detail page.

The example explained in this article can apply to the WooCommerce website also. One can use this technique and display related products without using any plugin. It will give you more control over the design and markup for your product page.

Get Your Consumer Key and Consumer Secret

When you decide to start with WooCommerce REST API you first need to get your consumer key and consumer secret. These keys are the identification for the store and necessary while giving a call to the WooCommerce API. You may read more about it on their documentation.

First, install the WooCommerce plugin on your website. Then head over to the WooCommerce->Settings page. Click on the Advanced tab and then on the REST API link.

woo rest api

On this page click on the button ‘Create an API Key’.

woo rest api

Enter the description, choose ‘Read’ permission, and hit the Generate API key button. You can choose ‘Read/Write’ permission also. It depends on your requirement. If you just need to read data from WooCommerce then choose the ‘Read’ option. And if you want to do both reads and write operations then your obvious option is ‘Read/Write’. Here we are targeting only on related products so ‘Read’ permission is sufficient.

wc rest api

Copy your consumer key and consumer secret which will be required while giving API calls.

woo rest api

WooCommerce REST API to Get Related Products

Once you are ready with your consumer key and consumer secret, we can start with the code which gives an API call to the WooCommerce endpoint. As we need to fetch related products first we need to get a single product’s data through the API. This is because we normally display our similar products on the single product page.

As we need to send HTTP requests, install the Guzzle library using the command below.

composer require guzzlehttp/guzzle

Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with web services.

Finally, let’s write a code to get a single product and then it’s related products. When WooCommerce returns the product’s data, in response it also contains the ‘related_ids’ key along with the values. These values are nothing but related products ids. So in context with this, our PHP code will be as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

define('WC_CONSUMER_KEY', 'PASTE_CONSUMER_KEY_HERE');
define('WC_CONSUMER_SECRET', 'PASTE_CONSUMER_SECRET_HERE');
 
$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'YOUR_DOMAIN_BASE_URL',
]);

try {
    $response = $client->request('GET', '/wp-json/wc/v3/products/PRODUCT_ID_HERE', [
        'headers' => [
            "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
        ],
        'verify' => false, //only needed if you are facing SSL certificate issue
    ]);
    
    $body = $response->getBody();
    $arr_body = json_decode($body);

    $response = $client->request('GET', '/wp-json/wc/v3/products', [
        'headers' => [
            "Authorization" => "Basic ". base64_encode(WC_CONSUMER_KEY.':'.WC_CONSUMER_SECRET)
        ],
        'query' => [
            'include' => $arr_body->related_ids,
        ],
        'verify' => false,
    ]);
    
    $body = $response->getBody();
    $arr_products = json_decode($body);

    if (!empty($arr_products)) {
        foreach ($arr_products as $product) {
            ?>
            <p>
                <a href="<?php echo $product->permalink; ?>"><?php echo $product->name; ?></a>
            </p>
            <?php
        }
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

Replace the placeholder ‘PRODUCT_ID_HERE’ with the actual value. In the above code, I am passing ‘includes’ parameter as an array with the related_ids. WooCommerce then in response gives us all the details about the products. Then we loop through it and display the product title and its link. The user can also print the other data from the response.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

1 thought on “How to Display Related Products Using WooCommerce REST API

Leave a Reply

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