3

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.

1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.