How to Add Rel Prev, Next tag in Magento 2

Search engine optimization plays an important role in any online store. It helps store owners make their website, content, or products become visible to audiences. That’s why it’s one of the most effective tools to use when it comes to online marketing.

In Magento 2, there are numerous options that can help you optimize your search engine. However, when it comes to category pages, you can only add canonical meta tags, which can lead to lots of inconveniences. Therefore, in this post, I will tell you the way to add rel="next" and rel="prev" tags in Magento 2 to support bots with paginated content.

Let’s start!

How to Add Rel Prev, Next tag in Magento 2 in 3 steps

Step 1: Configure the module to view specific events

There are various ways that could help you add Rel Prev, Next tag. However, I highly recommended using the event observer approach. In order to use this method, the first step you need to do is to configure the module to view specific events. To do this, you need to create an events.xml file in your extensions etc/frontend folder. Then, you can create your observer class.

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="layout_generate_blocks_after">
        <observer name="categorySeo" instance="Mageplaza\Seo\Observer\Category" />
    </event>
</config>

From the XML file above, you can see the event that is being observed is layout_generate_blocks_after. Because the above event is not exclusive to category pages, you will need to check if you are already on the category view page or not. And since the full action name has been included in the event object data, this is not really essential.

if ('catalog_category_view' != $observer->getEvent()->getFullActionName()) {
    return $this;
}

Step 2: Replace canonical tag’s default settings

In the default implementation, the canonical tag always points to the root category URL despite the applied page or filter combination.

You will need the category model instance if you want to remove the default canonical tag. To retrieve it, you can use the registry (current_category). In the following example, the layout object will be used because it’s a part of the event object data.

/** @var \Magento\Catalog\Block\Product\ListProduct $productListBlock */
$productListBlock = $observer->getEvent()->getLayout()->getBlock('category.products.list');
$category = $productListBlock->getLayer()->getCurrentCategory();
 
/**
 * Remove default canonical tag
 */
if ($this->categoryHelper->canUseCanonicalTag()) {
    $this->pageConfig->getAssetCollection()->remove($category->getUrl());
}

After the default tag has been removed, you can now add your own canonical tag. To add tag, you can generate your canonical URL by using pager block instance (\Magento\Theme\Block\Html\Pager) and insert it with page config (\Magento\Framework\View\Page\Config).

/** @var \Magento\Catalog\Block\Product\ProductList\Toolbar $toolbarBlock */
$toolbarBlock = $productListBlock->getToolbarBlock();
/** @var \Magento\Theme\Block\Html\Pager $pagerBlock */
$pagerBlock = $toolbarBlock->getChildBlock('product_list_toolbar_pager');
$pagerBlock->setAvailableLimit($toolbarBlock->getAvailableLimit())
    ->setCollection($productListBlock->getLayer()->getProductCollection());
 
/**
 * Add rel canonical with page variable
 */
$this->pageConfig->addRemotePageAsset(
    $this->getPageUrl([
        $pagerBlock->getPageVarName() => $pagerBlock->getCurrentPage()
    ]),
    'canonical',
    ['attributes' => ['rel' => 'canonical']]
);

You might notice that the method which I have just shown you is getPageUrl, which can be found in \Magento\Theme\Block\Html\Pager class. However I have customized it a bit to make it more suitable.

/**
* Retrieve page URL by defined parameters
*
* @param array $params
* @return string
*/
protected function getPageUrl($params = [])
{
    $urlParams = [];
    $urlParams['_current'] = false;
    $urlParams['_escape'] = true;
    $urlParams['_use_rewrite'] = true;
    $urlParams['_query'] = $params;
 
    return $this->urlBuilder->getUrl('*/*/*', $urlParams);
}

Step 3: Add rel="prev" and rel="next"

This is the final step in the adding process. In this step, you will add rel="prev" and rel="next" to indicate the paginated content. When adding these, the search engine bots will treat these pages in the order that you want. Then, their liking properties will be consolidated and customers will usually be sent to the first page.

/**
 * Add rel prev and rel next
 */
if (1 < $pagerBlock->getCurrentPage()) {
    $this->pageConfig->addRemotePageAsset(
        $this->getPageUrl([
            $pagerBlock->getPageVarName() => $pagerBlock->getCollection()->getCurPage(-1)
        ]),
        'link_rel',
        ['attributes' => ['rel' => 'prev']]
    );
}
if ($pagerBlock->getCurrentPage() < $pagerBlock->getLastPageNum()) {
    $this->pageConfig->addRemotePageAsset(
        $this->getPageUrl([
            $pagerBlock->getPageVarName() => $pagerBlock->getCollection()->getCurPage(+1)
        ]),
        'link_rel',
        ['attributes' => ['rel' => 'next']]
    );
}

Conclusion

After finishing all the above steps, you will now have a working code that can help you add canonical, rel="prev" and rel="next" meta tags to Magento 2. Although this is not a complete solution for SEO, it is still a good improvement to fix the weakness of default functionality. To have the full functions for SEO you can refer our SEO extension. I hope this tutorial is helpful for you. If you have any question, feel free to leave comments below. Thank you for reading!

Image Description
With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.
x