Add Configurable Products to Cart by SKU in Magento
Hello, developers! Today we’re going to tackle an interesting challenge: adding configurable products to your cart using only the product’s SKU. This comes up often when you need to programmatically manage products or recreate a user’s cart.
The Challenge at Hand
Our friend Marcin here is already familiar with adding products by ID to the cart:
$params = array(
'product' => 272,
'super_attribute' => array(22 => 30),
'qty' => 2,
);
He’s loading a product, setting parameters, and then boom â it goes straight into the cart. But there’s a catch: he only knows the product’s SKU, not its ID or attributes.
The Magic of LoadByAttribute()
Marcin tried using loadByAttribute('sku', '$sku'), which indeed loads the product by its SKU:
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
However, this only gives him basic product info. The crucial super_attributes are missing.
Diving Deeper: Finding Super Attributes
To solve this, we need to leverage Magento’s product type functionality. For configurable products:
- Load the parent product by SKU.
- Find its children (variations).
- Extract the desired variation based on your requirements (like color or size).
Here’s a step-by-step guide:
$sku = 'Your_SKU_Here';
$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
// Check if it's a configurable product
if ($product->getTypeId() == 'configurable') {
// Get all the children (variations)
$children = $product->getTypeInstance()->getUsedProducts(null, $product);
foreach($children as $child) {
// Here you can add logic to filter by super attributes
if ($child->getSku() == 'Your_Variation_SKU') {
// Got the correct variation
$variation = $child;
break; // Stop processing
}
}
// Now we have the correct product (variation)
$cart = Mage::getSingleton('checkout/cart');
$params = array(
'product' => $variation->getId(),
'qty' => 2,
);
$cart->addProduct($variation, $params);
$cart->save();
Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}
Conclusion: Mastering Configurable Products
Adding configurable products to the cart by SKU requires understanding Magento’s product types and variations. By loading the parent product, filtering its children, and setting the right parameters, you can get your desired variation into the cart with ease.
Remember, every store is unique, so you might need to adjust this code based on your specific configuration or attribute setup. The key takeaway is knowing how to interact with configurable products at a deeper level.
Happy coding! If you’re looking for more tips and tricks like these, be sure to check out LaravelCompany’s blog â we’re always sharing the latest insights on Magento and Laravel development.