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
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
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!