cancel
Showing results for 
Search instead for 
Did you mean: 

M2 - Get all categories from cross sell products

M2 - Get all categories from cross sell products

I have a specific thing that I want to make because I can't find a extension that comes close to what i need.

 

On this page: https://www.bhphotovideo.com/c/product/1318277-REG/canon_eos_rebel_t7i_dslr.html

 

When you click next to Recommended Accessories on "View all" you see a list of all compatible accessories for the product.

 

I want to make such thing with the cross sell products in Magento, I managed to get the cross sell products id and the categories where they in.

 

<?php
	//$myBlock = \Magento\Framework\App\ObjectManager::getInstance()->get('Mageplaza\HelloWorld\Block\HelloWorld');

	$crossSellProducts = $_product->getCrossSellProducts();	

	if( $crossSellProducts != "") {
		foreach ($crossSellProducts as $crossSellProduct) {

		$categoryCollectionCross = $crossSellProduct->getCategoryCollection();
?>
		Crosssell product: <?php echo $crossSellProduct->getSku(); ?><br>
		<?php 
			foreach ($categoryCollectionCross as $categoryCollectionCrossItem) { 
				$crossCategoryId = $categoryCollectionCrossItem->getId();
				$_objectManagerCat = \Magento\Framework\App\ObjectManager::getInstance();
				$categoryNameAv = $_objectManagerCat->create('Magento\Catalog\Model\Category')->load($crossCategoryId);
		?>
				Categorie ID: <?php echo $crossCategoryId; ?><br>
				Categorie Name: <?php echo $categoryNameAv->getName(); ?><br>
		<?php 
			}       
		echo "<br>";
		}
	}
?>

I know that making direct use of the Object Manager is not ideal, but I don't know a way to make it work with DI.

 

First thing I need is a list of the categories from the cross sell products so I can make navigation menu. But I don't want double categories.

 

Is there anyone who can help me with that?

1 REPLY 1

Re: M2 - Get all categories from cross sell products

Hello @Purple 

 

make one helper file and pass argument as category id.

 

in that helper file you will do what ever logic and call that helper into that file.

 


Problem solved? Click Kudos & Accept as Solution!
Sunil Patel
Magento 2 Certified Professional Developer & Frontend Developer