0

Under my product page, I wish to have some products shown from the same category.

How can I achieve this in Magento 2 without having to manually set the related products?

Thanks

3
  • 1
    You can add Related products Commented May 11, 2018 at 9:09
  • please specify that is your Version of M1 or M2?
    – Divyesh
    Commented May 11, 2018 at 9:16
  • Edited post with M2. @hewb75 - The point is for Magento to automatically show them by what category they are in rather than me adding related products for thousands of products.
    – zcoyne
    Commented May 11, 2018 at 14:15

1 Answer 1

1

Please try the below code in your product detail page template.

For Current product category ids

<?php 
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$product = $objectManager->get('Magento\Framework\Registry')->registry('current_product');
$categories = $product->getCategoryIds(); /*will return category ids array*/

?>

Load the product by category id

     $categoryId=" Take the id from your current product categories array"
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $category= $objectManager->get('Magento\Catalog\Model\CategoryFactory')->create()->load($categoryId);
        $collection = $objectManager->get('Magento\Catalog\Model\ResourceModel\Product\CollectionFactory')->create()
        $collection->addAttributeToSelect('*');
        $collection->addCategoryFilter($category);
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
       collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
return $collection;

Hope it will help you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.