Magento – Link to configurable product with specific values selected

configurable-productmagento2

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.

Best Answer

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 : '');
}