Sort products at the bottom of the product list in cart WooCommerce by SKU
The following code will sort products last, based on the product sku
Related thread:
function sort_cart_specific_product_at_bottom( $cart ) { // Product sku to to display at tbe bottom of the product list $product_sku_last = array( 'lunchbox', 'pakket' ); // Set empty arrays $products_in_cart = array(); $products_last = array(); $cart_contents = array(); // Loop through cart items foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) { // Get product sku $product_sku = $cart_item['data']->get_sku(); // Get product id $product_id = $cart_item['data']->get_id(); // In_array — checks if a value exists in an array if ( in_array( $product_sku, $product_sku_last ) ) { // Add to products last array $products_last[ $cart_item_key ] = $product_id; } else { // Add to products in cart array $products_in_cart[ $cart_item_key ] = $product_id; } } // Merges the elements together so that the values of one are appended to the end of the previous one. $products_in_cart = array_merge( $products_in_cart, $products_last ); // Assign sorted items to cart foreach ( $products_in_cart as $cart_item_key => $product_id ) { $cart_contents[ $cart_item_key ] = $cart->cart_contents[ $cart_item_key ]; } // Cart contents $cart->cart_contents = $cart_contents;}add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_specific_product_at_bottom', 10, 1 );
And this code ensures that the items based on sku are not removable from the shopping cart
function prevent_cart_item_remove_link( $link, $cart_item_key ) { // Product sku that should not be removable $product_sku_last = array( 'lunchbox', 'pakket' ); if( WC()->cart->find_product_in_cart( $cart_item_key ) ) { $cart_item = WC()->cart->cart_contents[ $cart_item_key ]; // Get product sku $product_sku = $cart_item['data']->get_sku(); // In_array — checks if a value exists in an array if ( in_array( $product_sku, $product_sku_last ) ) { $link = ''; } } return $link;}add_filter( 'woocommerce_cart_item_remove_link', 'prevent_cart_item_remove_link', 10, 2 );