Question

I need to show related products block on configurable product page (as it is by deflault), but instead of related products of configurable product i need to show related products of simple products which are included in that configurable product.

Was it helpful?

Solution

If you want to display related products of child items instead of the related products of the parent item in a configurable product structure, then

Create a new module and override _prepareData function the main block file

vendor/magento/module-catalog/Block/Product/ProductList/Related.php

Something like

protected function _prepareData() {
    $product = $this->_coreRegistry->registry('product');
    /* @var $product \Magento\Catalog\Model\Product */

    // GET TYPE
    $productType = $product->getTypeId();

    // IF CONFIGURABLE
    if ($productType == 'configurable') {
        $childrenProducts = $product->getTypeInstance()->getUsedProducts($product);
        if ($childrenProducts) {
            $this->_itemCollection = array();
            foreach ($childrenProducts as $singleChild) {
                $relatedProductCollection = $singleChild->getRelatedProductCollection()->addAttributeToSelect(
                                'required_options'
                        )->setPositionOrder()->addStoreFilter();

                if ($this->moduleManager->isEnabled('Magento_Checkout')) {
                    $this->_addProductAttributesAndPrices($relatedProductCollection);
                }
                $relatedProductCollection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
                $relatedProductCollection->load();
                foreach ($relatedProductCollection as $singleProduct) {
                    $singleProduct->setDoNotUseCategoryId(true);
                    $this->_itemCollection[] = $singleProduct;
                }
            }
        }
    } else {
        // IF OTHERS

        // main FUNCITON CODE
    }


    return $this;
}

and then override the items.phtml file

vendor/magento/module-catalog/view/frontend/templates/product/list/items.phtml

under case 'related' change the if condition

if ($exist = $block->getItems()->getSize())

to

if ($exist = count($block->getItems()))
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top