woocommerce cart page display products order by product price

I have develop shoping cart in wordpress using Woocommerce plugin. I need to display products in the cart order by product price please help me to do this

thanks

Related posts

Leave a Reply

3 comments

  1. To order products low to high or high to low price in the Woocommerce cart, try adding the following to your functions.php file (or plugin):

    function 12345_cart_updated() {
    
        $products_in_cart = array();
        // Assign each product's price to its cart item key (to be used again later)
        foreach ( WC()->cart->cart_contents as $key => $item ) {
            $product = wc_get_product( $item['product_id'] );
            $products_in_cart[ $key ] = $product->get_price();
        }
    
        // SORTING - use one or the other two following lines:
        asort( $products_in_cart ); // sort low to high
        // arsort( $products_in_cart ); // sort high to low
    
        // Put sorted items back in cart
        $cart_contents = array();
        foreach ( $products_in_cart as $cart_key => $price ) {
           $cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
        }
    
        WC()->cart->cart_contents = $cart_contents;
    
    }
    add_action( 'woocommerce_cart_loaded_from_session', '12345_cart_updated' );
    

    This function is similar and derived from one seen at https://businessbloomer.com/woocommerce-sort-cart-items-alphabetically-az/ which is nearly identical to this earlier-posted function: https://gist.github.com/maxrice/6541634

  2. In most cases, for manipulating data on the WordPress ecosystem, the answer will be wp filter, no wp action.

    In addition, WC_car.cart_contents array, hold the product object it’s self on $cart_contents['data']; //WC_Product_Object, So we didn’t need to get product again.

    Simple filter to order by price:

    PHP 7.4+

    add_filter( 'woocommerce_get_cart_contents', 'prefix_cart_items_order' );
    function prefix_cart_items_order( $cart_contents ) {
      uasort($cart_contents, 
             fn($a, $b) => 
                 $a['data']->get_price() < $b['data']->get_price() ? -1 : 1
      );
      return $cart_contents;
    }
    

    PHP < 7

    add_filter( 'woocommerce_get_cart_contents', 'prefix_cart_items_order' );
    function prefix_cmp ($a, $b) { 
      return $a['data']->get_price() < $b['data']->get_price() ? -1 : 1;
    }
    function prefix_cart_items_order( $cart_contents ) {
      uasort($cart_contents, 'prefix_cmp');
      return $cart_contents;
    }