Sorting Magento Order Items: A Comprehensive Guide
Dear Magento developer,
I understand your frustration with trying to sort order items alphabetically instead of chronologically. Let’s dive into how you can achieve this for both the PDF invoice and the adminhtml orders table.
Understanding the Current Sorting Behavior
Magento, by default, sorts ordered items based on when they were added to the cart or placed in an order. This chronological sorting is not ideal for picking and packing purposes. You’d likely prefer a logical sorting like alphabetical (by SKU, name, or category).
Sorting Magento Order Items: The Approach
We’ll need to modify two key files to achieve this:
app/design/frontend/default/yourtheme/template/sales/order/invoice rendersInvoice.phtml- For the PDF invoiceapp/design/adminhtml/default/default/template/sales/order/view/items.phtml- For adminhtml orders
Sorting Magento Order Items by Name (Alphabetically)
Let’s tackle sorting by name first, as it appears to be your preferred method.
1. Modifying the PDF Invoice File
Open rendersInvoice.phtml and locate this section of code:
<?php $_items = $this->getInvoice()->getAllItems() ?>
<?php $_i=0;foreach ($_items as $_item): ?>
<?php if ($_item->getParentItem()) continue; else $_i++; ?>
<tbody class="<?php echo $_i%2?'even':'odd' ?>">
<?php echo $this->getItemHtml($_item) ?>
<?php echo $this->getItemExtraInfoHtml($_item->getOrderItem()) ?>
</tbody>
<?php endforeach; ?>
Replace it with this sorted version:
<?php $_items = $this->getInvoice()->getAllItems() ?>
<?php $_sortedItems = array(); ?>
<?php foreach ($_items as $_item) : ?>
<?php $_sortedItems[$_item->getName()] = $_item;?>
<?php endforeach;?>
<?php ksort($_sortedItems); ?>
<?php $i=0;foreach ($_sortedItems as $_item):?>
<?php if ($_item->getParentItem()) continue; else $i++;?>
<tbody class="<?php echo $i%2?'even':'odd' ?>">
<?php echo $this->getItemHtml($_item) ?>
<?php echo $this->getItemExtraInfoHtml($_item->getOrderItem()) ?>
</tbody>
<?php endforeach; ?>
This code sorts the order items by name before rendering them in the PDF invoice.
Sorting Magento Order Items by SKU
If you prefer sorting by SKU instead of name, simply replace $_sortedItems[$_item->getName()] with $_sortedItems[$_item->getSku()].
Remember to flush your Magento cache after making these changes for them to take effect.
Conclusion: Sorting Magento Order Items Made Easy
In this post, we’ve walked through the process of sorting Magento order items by name and SKU. These modifications allow you to display ordered items in a more logical sequence, making picking and packing more efficient.
If you found this guide helpful, please share it with your fellow developers. And if you’re looking for more advanced Magento customizations, feel free to explore the Magento development resources on our blog at Laravel Company.
Happy sorting!
- The Laravel Company Team