
How to Group WooCommerce Products on Shopping Cart
- May 17, 2016
- Leave a comment
WooCommerce provides you many useful hooks (actions/filters) to perform different functionalities on content manipulation and display setup. In this article, we will describe the method of grouping WooCommerce products of the same author/vendor on a WordPress website.
The products on shipping calculator will be grouped using woocommerce_cart_shipping_packages filter. You just need to insert the following code in your Theme’s functions.php file or custom plugin:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<?php class pt_woo_cart_group { public function __construct() { add_filter('woocommerce_cart_shipping_packages', array($this, 'group_cart')); } /** * Grouping cart by products' authors/vendors * using filter woocommerce_cart_shipping_packages * * @param array $packages * @return array */ public function group_cart($packages) { // Reset the packages $packages_reset = array(); $i = 0; foreach (WC()->cart->get_cart() as $cart_index => $item) { $item_data = $item['data']; if ($item_data->needs_shipping()) { $post_author = get_post_field('post_author', $item_data->id); $packages_reset[$post_author]['contents'][] = $item; $packages_reset[$post_author]['shipping_options'] = $packages[$i]['shipping_options']; $packages_reset[$post_author]['applied_coupons'] = WC()->cart->applied_coupons; $packages_reset[$post_author]['destination'] = $packages[$i]['destination']; } $i++; } // merging manipulation of prices foreach ($packages_reset as $package_ind => $package_reset) { $packages_reset[$package_ind]['contents_cost'] = array_sum(wp_list_pluck($package_reset, 'line_total')); } return $packages_reset; } } new pt_woo_cart_group(); |
Hello there,
How would I go about adjusting this to group products in their respective categories?
Category 1
– Product 3
– Product 7
Category 2
– Product 5
– Product 1
Thanks 🙂
Sven