I want to display all product url in frontend with category name inside, I had checked all the configuration, but didn't find anything. Now I think I have to do it by coding, please guide me little bit how to start?
3 Answers
Create your extension and Overwrite product list page, product details page. after that create block and call below function were you want category url.
nameSpace ['Your_nameSpace']
use Magento\Catalog\Api\CategoryRepositoryInterface;
class ['Your_Class_name']
protected $_registry;
public function __construct(
\Magento\Framework\Registry $registry
) {
.........
$this->_registry = $registry;
}
public function getCategory()
{
$current_category = $this->_registry->registry('current_category');
return $current_category->getUrl();
}
}
You can create a function in helper and call in the phtml file where you want to show.
public function getProductCategoryName($product)
{
$html = '';
$categories = $product->getCategoryIds(); /*will return category ids array*/
foreach($categories as $category){
$cat = $this->_objectManager->create('Magento\Catalog\Model\Category')->load($category);
$html.= "<span class='product-category'>";
$html.= $cat->getName();
$html.= '</span>';
}
return $html;
}
Suppose product assigned in multiple category. In phtml file, you can call below code:
<?php
echo $helper->getProductCategoryName($product);
?>
Hope this can help.