magento web developer

Manchester based Magento and Zend Framework certified developer.

Add products to the cart (in code)

Sometimes it is quite useful to be able to add products to a customer’s cart in code.  For example, you may wish to launch an email promotion with a link to the store. When the user clicks the link, they are directed straight to the cart page on the merchant’s website with the promoted product already in their cart!

Simple Products

Adding simple products is very easy and can be achieved with the following code:

// ...
$cart = Mage::getSingleton('checkout/cart');
$product = Mage::getModel('catalog/product')

// or...

// ...

Configurable Products

Things get a bit more complex when you need to add a configurable product and you need to prepare a ‘request’ array with the following structure.

'super_attribute' =>
    [attribute_id] => [attribute_value_id],
    [attribute_id_2] => [attribute_value_id_2],
'qty' => [qty]

First up, you need to obtain the attribute id and attribute value id.

$attribute = Mage::getModel('catalog/product')

$attributeId = $attribute->getId();
$attributeValueId = $attribute

And then implement the structure in PHP as follows:

$cart = Mage::getSingleton('checkout/cart');

$request = array();
$request['qty'] = 1;
$request['super_attribute'] = array();
$request['super_attribute'][65] = 1;
$request['super_attribute'][66] = 12;

$cart->addProduct(1242, $request);

Navigate to the directory you just created

I’ve wanted to know if this was possible for ages, and I’ve only just found out it is!
You can navigate back to the directory you’ve just created (or even just referenced) with the following:

$ mkdir -p test/me
$ cd !$

Another useful tool is there also, mkdir -p creates a structure of directories, rather than creating one at a time.

Copy whilst preserving directory structure

$ cp --parents /a/directory/structure/file.txt /target/folder

This will copy file.txt from the folder you are in, and place it in the same folder structure, in the target folder.  The end result will look like this:


One-off Magento scripts

Sometimes it is useful to be able to run quick scripts outside of Magento.  This is possible by placing the following at the top of a script in the Magento root:


// you now have the Magento environment setup to do things like this...
$product = Mage::getModel('catalog/product')->load(123);

Check for null and empty strings in one

Today I discovered that you can avoid:

SELECT * FROM table_name WHERE value IS NOT NULL AND value != '';

And instead use:

SELECT * FROM table_name WHERE value > '';

This checks that the value is both not null, and not an empty string in one go. Okay, it’s not as readable, but it’s good for quick queries.

1 2