Skip to content

Instantly share code, notes, and snippets.

@noogen
Last active June 1, 2020 06:47
Show Gist options
  • Save noogen/acbd201e6a7ce71a2c2205a1cd994c60 to your computer and use it in GitHub Desktop.
Save noogen/acbd201e6a7ce71a2c2205a1cd994c60 to your computer and use it in GitHub Desktop.
Wordpress Cart sorting with woo-extra-product-options plugin
add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_alphabetically' );
function sort_cart_items_alphabetically() {
global $woocommerce;
// Read Cart Items
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
// sort by title by default
$products_in_cart[ $key ] = $item['data']->get_title();
// sort by woo-extra-product-options->custom_item field
$extra_options = isset($item['thwepof_options']) ? $item['thwepof_options'] : false;
if($extra_options){
$products_in_cart[ $key ] = $extra_options['custom_item']['value'];
}
}
// Sort Cart Items
natsort( $products_in_cart );
// Assign Sorted Items to Cart
$cart_contents = array();
foreach ( $products_in_cart as $cart_key => $v ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment