How to Display Related Products Using WooCommerce REST API

If you running an online store it is recommended to show related products on the product page. It helps your customers to see similar products they wish to buy. With this little trick, you can increase user engagement on your website. As more time customers spend in the store, there are high chances of buying your products.

In this article, I show you how to show related products using the WooCommerce REST API. I will fetch all products related to the current product and print the name of a product. I also link each product to its detail page. In WooCommerce, products can be related to each other in three ways: Up-Sells, Cross-Sells, or by having the same tags or categories.

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

Get Your Consumer Key and Consumer Secret

To interact with the WooCommerce REST API, you first need to get your consumer key and consumer secret. These keys are used for authentication purposes and are required while giving a call to the REST API. You may read more about it in their documentation. The user requires to send these keys in the Authorization header.

Note : If you are not using HTTPS on your website, then instead of WooCommerce API keys use the application password provided by WordPress. Follow the linked article where I explain how to use it with REST API.

Grab these keys by visiting 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 also choose ‘Read/Write’ permission. It depends on your requirement. If you just need to read data from WooCommerce then the ‘Read’ option is sufficient. Choose the ‘Read/Write’ option if you want to do both read/write operations. Here we are targeting related products so I have chosen ‘Read’ permission.

wc rest api

Copy your consumer key and consumer secret which will be required in the next steps.

woo rest api

Get Related Products using WooCommerce REST API

You are now ready with your API credentials. We can start with the code which sends an API request to the WooCommerce REST API endpoints. To fetch related products, we first need to get a single product’s data through the API. In the same response, WooCommerce gives related products ids.

As we have 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 its related products. When WooCommerce returns the product’s data, in response it keeps the array of related_ids. These values are nothing but ids of related products.

<?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);

    if (!empty($arr_body->related_ids)) {
        $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
            }
        }
    } else {
        echo "No related products found.";
    }
} catch (Exception $e) {
    echo $e->getMessage();
}

Replace the placeholder ‘PRODUCT_ID_HERE’ with the actual product id. In the code, I am passing the ‘includes’ parameter as an array with the related_ids. In response, WooCommerce gives details about these products. We loop through these products and display the product title along with a 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.