Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

wp wc php sort products archive cheapest price

add_action( 'woocommerce_cart_loaded_from_session', 'prefix_cart_order_prod_cat' );
/**
 * WooCommerce - sort cart order by price
 * @link https://stackoverflow.com/questions/17194899/woocommerce-cart-page-display-products-order-by-product-price/57136404#57136404
 */
function prefix_cart_order_prod_cat() {

    $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;

}
Source by wpbeaches.com #
 
PREVIOUS NEXT
Tagged: #wp #wc #php #sort #products #archive #cheapest #price
ADD COMMENT
Topic
Name
5+3 =