This article shows how you can load any configurable product in Magento with the configurable options pre-selected.
We can append the Attribute-OptionValue hash value (#Attribute_ID=Value_ID
) at the end of the configurable product URL.
For example, let’s suppose that the configurable product URL is:
https://example.com/my-configurable-product.html
We can add the attribute option values like this:
https://example.com/my-configurable-product.html#802=130&805=187
#Attribute_ID=Value_ID
802 = Attribute ID
130 = Option value ID of the above attribute
805 = Attribute ID
187 = Option value ID of the above attribute
The following function can be used to generate the Attribute-OptionValue
Hash.
/**
* Get attribute=value hash to be appended in the product URL
* e.g. #802=130&805=187
* #Attribute_ID=Value_ID
* Appending hash in the configurable product URL will help in
* auto-selecting the configurable options like color, size, etc.
*
* @param $simpleProduct
* @param $configurableProduct
* @return string
*/
public function getAttributeHash($simpleProduct, $configurableProduct)
{
try {
$configurableType = $configurableProduct->getTypeInstance();
$attributes = $configurableType->getConfigurableAttributesAsArray($configurableProduct);
$options = [];
foreach ($attributes as $attribute) {
$id = $attribute['attribute_id'];
$value = $simpleProduct->getData($attribute['attribute_code']);
$options[$id] = $value;
}
$options = http_build_query($options);
return $options ? '#' . $options : '';
} catch (\Exception $e) {
$this->logger->error($e->getMessage());
}
}
Hope this helps. Thanks.