4

Similar to this, but with Magento 2

I want to load a configurable product page, with pre-selected attribute value.

My final purpose is to replace the simple product's url in the catalog with the "parent" configurable's url, with the selected attribute values from the simple product.

I have retrieved the "parent" configurable's url for every product, and i have replaced it with the simple product's url in the catalog. I am missing a way to load the configurable's product page, with different selected values each time.

2 Answers 2

2

I adapted my answer from this code snippet here...

This method will take a configured product and a simple child product and return the "hash" URL that preselects the variant. The key method doing the work here is getConfigurableAttributesAsArray()

 /**
 * @param \Magento\Catalog\Model\Product $parentProduct
 * @param \Magento\Catalog\Model\Product $simpleProduct
 * @return string Hashed Url
 */
public function getHashUrl($parentProduct, $simpleProduct)
{
    $configType = $parentProduct->getTypeInstance();
    $attributes = $configType->getConfigurableAttributesAsArray($parentProduct);
    $options = [];
    foreach ($attributes as $attribute) {
        $id = $attribute['attribute_id'];
        $value = $simpleProduct->getData($attribute['attribute_code']);
        $options[$id] = $value;
    }
    $options = http_build_query($options);
    return $parentProduct->getProductUrl().($options ? '#' . $options : '');
}
0

To preselect a simple product in a configurable product, the address of a simple product should look like this for example:

/mona-pullover-hoodlie.html#143=167&93=53

where

/mona-pullover-hoodlie.html - configurable product URL,

143, 93 - attributes IDs,

167, 53 - option IDs.

In order to change the URL of simple products, you can create a Plugin (Interceptor) for Magento\Catalog\Model\Product::getProductUrl(), where to generate the URL as in the example above.


I made VCT Simple Product URL module on Magento Marketplace that solves this problem.

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.