Skip to main content

How to Get the Configurable Product of a Child in Magento2

How to Get the Configurable Product of a Child in Magento2

 

in order to get the Parent product of a child you will need the child product id then you can get the parent by this code

use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\ConfigurableProduct\Model\ResourceModel\Product\Type\Configurable;
class GetConfigurableProduct
{
    protected $productRepository;
    protected $configurable;
    public function __construct(
        ProductRepositoryInterface $productRepository,
        Configurable $configurable
    ) {
        $this->productRepository = $productRepository;
        $this->configurable = $configurable;
    }
    public function getConfigurableProductByChildId($simpleProductId)
    {
        // Get parent configurable product IDs
        $parentIds = $this->configurable->getParentIdsByChild($simpleProductId);
        
        if (!empty($parentIds)) {
            // Load first configurable product
            return $this->productRepository->getById($parentIds[0]);
        }
        return null;
    }
}

and to get the canonical URL for any product you can use this code

 

$product->getUrlModel()->getUrl($$product, ['_ignore_category' => true]);
$canonical_url = $product->getRequestPath();