Last active
June 1, 2020 06:47
-
-
Save noogen/acbd201e6a7ce71a2c2205a1cd994c60 to your computer and use it in GitHub Desktop.
Wordpress Cart sorting with woo-extra-product-options plugin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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