I have a custom module. I want to display category name of each product in the cart
Please see my code
checkout_index_index.xml
<body>
<referenceBlock name="additional.product.info">
<block class="Company\Module\Block\Showcategory" name="showcategory" template="Company_Module::checkout/cart/categoryname.phtml"/>
</referenceBlock>
</body>
categoryname.phtml
<?php $quoteItems = $block->getCheckoutSession(); ?>
<?php echo count($quoteItems); ?>
<?php foreach ($quoteItems as $item):
$pid = $item->getProductId();
$product = $block->getProductRepository()->getById($pid);
$cats = $product->getCategoryIds();
foreach ($cats as $category_id) {
$_cat = $block->getCategoryRepository()->get($category_id, $block->getStoreId());
echo $_cat->getName();
}
?>
<?php endforeach; ?>
Showcategory.php
<?php
namespace Company\Module\Block;
use Magento\Framework\View\Element\Template\Context;
use Magento\Checkout\Model\Session;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\CategoryRepositoryInterface;
use Magento\Store\Model\StoreManagerInterface;
class Showcategory extends \Magento\Framework\View\Element\Template
{
/** @var CheckoutSession */
private $checkoutSession;
/** @var ProductRepository */
private $productRepository;
/** @var CategoryRepository */
private $categoryRepository;
/** @var StoreManager */
private $storeManager;
/**
* @param CheckoutSession $checkoutSession
* @param ProductRepository $productRepository
* @param CategoryRepository $categoryRepository
* @param StoreManager $storeManager
*/
public function __construct(
Context $context,
Session $checkoutSession,
ProductRepositoryInterface $productRepository,
CategoryRepositoryInterface $categoryRepository,
StoreManagerInterface $storeManager,
array $data = []
) {
parent::__construct($context, $data);
$this->checkoutSession = $checkoutSession;
$this->productRepository = $productRepository;
$this->categoryRepository = $categoryRepository;
$this->storeManager = $storeManager;
}
public function getCheckoutSession() {
$quote = $this->checkoutSession->getQuote();
$items = $quote->getAllVisibleItems();
return $items;
}
public function getProductRepository() {
$product = $this->productRepository;
return $product;
}
public function getCategoryRepository() {
$category = $this->categoryRepository;
return $category;
}
public function getStoreId() {
$storeId = $this->storeManager->getStore()->getId();
return $storeId;
}
}
But it is showing all category names under each product. Please refer the image
Please advice
Best Answer
checkout_cart_index.xml
Gaurav\Companyname\Block\Showcategory.php
Gaurav\Companyname\view\frontend\templates\categoryname.phtml