Skip to content

Instantly share code, notes, and snippets.

@noogen
Last active June 1, 2020 06:47
Show Gist options
  • Select an option

  • Save noogen/acbd201e6a7ce71a2c2205a1cd994c60 to your computer and use it in GitHub Desktop.

Select an option

Save noogen/acbd201e6a7ce71a2c2205a1cd994c60 to your computer and use it in GitHub Desktop.

Revisions

  1. noogen renamed this gist Jun 1, 2020. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. noogen created this gist Jun 1, 2020.
    30 changes: 30 additions & 0 deletions sort_cart.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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;

    }