1

I understand that getGrandTotal() will get the total price of the cart.

But now, I'd like to know how to get the total price of the cart based on product category in a cart?

I need this because there are different delivery charges based on the different categories in the site.

Thank you for the help!

  • You will need to loop through all items in cart. then get product id from item object inside loop and then you can get category id from product id. – Mohit chauhan Mar 25 at 7:37
0

You can get the category ids to which a product is assigned and sum up whatever value is relevant for your calculation (price incl. tax, price, row total,...). In my example I use the row total.

Theoeretically a product can be assigned to more than one category. The bellow code will work for example in the cart template (cart.phtml). If you wan't to use it somewhere else, you just have to load the quote model in your context and get the items with getAllItems().

//array that will contain an entry for each category id an the total of the items assigned
$categoryTotals = [];
foreach($this->getItems() as $item){
    //get the array of category ids wo which a product is assigned
    $categoryIds = $item->getProduct()->getCategoryIds();
    //add the row total (i.e. price * qty) to the specific category id
    foreach ($categoryIds as $categoryId){
        if (isset($categoryTotals[$categoryId])){
            $categoryTotals[$categoryId] += $item->getRowTotal();
        } else {
            $categoryTotals[$categoryId] = $item->getRowTotal();
        }
    }
}
  • thank you for your comment! Appreciate it. Yes I'm doing it on the shipping carrier page so I'd need to use getAllItems(). Let me enhance your code and get back to you, thank you! – DLLH Mar 25 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.