Ubercart Attributes
Attributes are not a very well documented part of Ubercart. I was looking to add products with a "Size" attribute to the cart programatically. I found a good number of people looking to solve similar problems, but none with a good solution. Here's what I found:
The Function
uc_cart_add_item() can be called manually to add products to the cart. Calling it with just the node id, like so
uc_cart_add_item('1');
will add one of that item (without attributes) to the cart.
The Parameters
Its full function definition is this:
uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE)
The ubercart api doesn't explain what each parameter does. The first are pretty easy to figure out, but the third looks like it could be anything, and it turns out it can.
$data
uc_attribute looks for $data to have the following array element
$data = array(
'attributes' => array(
$aid => $oid,
),
);
Where $aid is the Attribute id and $oid is the Option id.
Bring It Together
Let's say our store sells chocolate ($nid = 1). We want customers to be able to choose how large their chocolate is, so we create a 'Size' attribute ($aid = 1). Our chocolates are 2oz, 12oz, and 32oz ($oid = 1, 2, and 3 respectively). Adding one 12oz chocolate to the cart can be done pretty simply
$nid = 1;
$qty = 1;
$data = array(
'attributes' => array(
'1' => '2',
),
);
uc_cart_add_items($nid, $qty, $data);