I'm attempting to improve SEO for my product catalog by implementing the <link rel='next' href='..'>
and <link rel='prev' href='..'>
head meta tags for catalog pages with several pages of items.
After searching around quite a bit, I found the following solution [Source
] but no way to accomplish the same task in Magento 2.
How can I accomplish the same thing in Magento 2?
$actionName = $this->getAction()->getFullActionName();
if ($actionName == 'catalog_category_view') // Category Page
{
$category = Mage::registry('current_category');
$prodCol = $category->getProductCollection()->addAttributeToFilter('status', 1)->addAttributeToFilter('visibility', array('in' => array(Mage_Catalog_Model_Product_Visibility::VISIBILITY_IN_CATALOG, Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)));
$tool = $this->getLayout()->createBlock('page/html_pager')->setLimit($this->getLayout()->createBlock('catalog/product_list_toolbar')->getLimit())->setCollection($prodCol);
$linkPrev = false;
$linkNext = false;
if ($tool->getCollection()->getSelectCountSql()) {
if ($tool->getLastPageNum() > 1) {
if (!$tool->isFirstPage()) {
$linkPrev = true;
if ($tool->getCurrentPage() == 2) {
$url = explode('?', $tool->getPreviousPageUrl());
$prevUrl = @$url[0];
}
else {
$prevUrl = $tool->getPreviousPageUrl();
}
}
if (!$tool->isLastPage()) {
$linkNext = true;
$nextUrl = $tool->getNextPageUrl();
}
}
}
if ($linkPrev) echo '<link rel="prev" href="' . $prevUrl . '" />';
if ($linkNext) echo '<link rel="next" href="' . $nextUrl . '" />';
}
Best Answer
I've found a workaround for magento2 to accomplish this, which I've published here, but for the sake of it being here should the gist go somewhere, I'll include the code below.
Basically, we just create a block that we include for catalog_category_view that checks the current selected category, and tries its best to figure out the paging.
There were some strange bugs in using the pager itself to generate the urls in which for some reason it wouldn't go past a certain page number if we had the limiting somewhat low (eg: 8 per page), and thus, workarounds were made.
If anyone has any suggestions or ways to improve this, i'd love to hear about it, but this works for now.