Forum
Product Category in Cart
This is definitely the last one before Christmas, but I can't work it out!
I am trying to access the category
of products that are in my cart. I have done this to get the cart as an array:
$rawCart = perch_shop_cart([
'skip-template'=> true
]);
Then I am going through the items to create a little bit of javascript for each for sending to my analytics:
function getItemJs($item) {
if ($item['category']['0'] == 1) {
$category = 'Bulldog';
}
elseif ($item['category']['0'] == 2) {
$category = 'Club';
}
elseif ($item['category']['0'] == 3) {
$category = 'Ship';
}
elseif ($item['category']['0'] == 4) {
$category = 'Corgi';
}
elseif ($item['category']['0'] == 5) {
$category = 'Drummer';
}
elseif ($item['category']['0'] == 6) {
$category = 'Electric';
}
elseif ($item['category']['0'] == 7) {
$category = 'Liberty';
}
elseif ($item['category']['0'] == 8) {
$category = 'Cube';
}
elseif ($item['category']['0'] == 9) {
$category = 'Woof';
}
elseif ($item['category']['0'] == 10) {
$category = 'King';
}
elseif ($item['category']['0'] == 12) {
$category = 'Blip';
}
else {
$category = 'Unknown';
}
return <<<HTML
ga('ec:addProduct', {
'id': '{$item['sku']}',
'name': '{$item['title']}',
'price': '{$item['price_with_tax']}',
'quantity': '{$item['qty']}',
'category': '{$category}'
});
HTML;
}
foreach ($rawCart['items'] as $item) {
echo getItemJs($item);
}
My problem is that category
is not present in the array where I would expect it. If I do a showall
in a template I get what I would expect:
[category] => Array
(
[0] => 6
)
But in my $rawCart
array the category information is not there. I have used the process above with perch_shop_order_items
and it has worked perfectly, but this has me stumped
How can I access the category to output it to my javascript?
Thanks for your help as always!
Mike
Categories aren't held in the cart, no. You'll need to look up the product and find the categories from there.