Sort order items by SKU in Woocommerce admin order pages [duplicate]

假如想象 提交于 2020-07-23 07:37:09

问题


I'm stumped if it's possible. I have scouted to only seeing results to sort by SKU on the front end. not the backend. When you edit an order, I want there to be an SKU column that I can sort by ASC/DESC. Is there a plugin out there that achieves this, or a snippet of code that can add in an additional column? Any help would be greatly appreciated. Below is an image illustrating the SKU I'm talking about and would love for it to be moved/duplicated into its own column


回答1:


add_filter( 'woocommerce_order_get_items', 'filter_order_get_items', 10, 3 );
function filter_order_get_items( $items, $order, $types = 'line_item' ) {

    if(count($items) < 2) return $items;

    if( $types != 'line_item') return $items;

    $item_skus = $sorted_items = array();

    // Loop through order line items
    foreach( $items as $items_id => $item ){
        // Check items type: for versions before Woocommerce 3.3
        if($item->is_type('line_item')){
            $product = $item->get_product(); //
            $item_skus[$product->get_sku()] = $items_id;
        }
    }
    // Check items type: for versions before Woocommerce 3.3 (2)
    if( count($item_skus) == 0 ) return $items;

    // Sorting in ASC order based on SKUs;
    ksort($item_skus); // or use krsort() for DESC order

    // Loop through sorted $item_skus array
    foreach( $item_skus as $sku => $item_id ){
        // Set items in the correct order
        $sorted_items[$item_id] = $items[$item_id];
    }
    return $sorted_items;
}



回答2:


@mujuonly has a great answer. I was using it until I found a conflict with woocommerce subscription renewals. The original orders were fine, but renewals orders were missing their shipping method.

Instead I opted to sort the basket items by sku so that they would be saved in the database that way.

add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_sku' );

function sort_cart_items_sku() {

    // READ CART ITEMS
    $products_in_cart = array();
    foreach ( WC()->cart->get_cart_contents() as $key => $item ) {
        $products_in_cart[ $key ] = $item['data']->get_sku();
    }

    // SORT CART ITEMS
    natsort( $products_in_cart );

    // ASSIGN SORTED ITEMS TO CART
    $cart_contents = array();
    foreach ( $products_in_cart as $cart_key => $product_title ) {
        $cart_contents[ $cart_key ] = WC()->cart->cart_contents[ $cart_key ];
    }
    WC()->cart->cart_contents = $cart_contents;

}

Credit: https://businessbloomer.com/woocommerce-sort-cart-items-alphabetically-az/



来源:https://stackoverflow.com/questions/54797925/sort-order-items-by-sku-in-woocommerce-admin-order-pages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!