我正在寻找一个 php 片段,根据迷你购物车/购物车、结帐页面和感谢页面中的 sku 对 woocommerce 产品进行排序。 下面的代码片段在商店中运行良好,但不适用于其他商店。 预先感谢您。
add_filter('woocommerce_get_catalog_ordering_args', 'am_woocommerce_catalog_orderby');
function am_woocommerce_catalog_orderby( $args ) {
$args['meta_key'] = '_sku';
$args['orderby'] = '_sku';
$args['order'] = 'asc';
return $args;
}
基于 使用 Dokan 插件时按供应商对 WooCommerce 购物车项目进行排序,以下是按 SKU 对购物车项目进行排序的方法(适用于购物车项目、迷你购物车项目和订单项目):
add_action( 'woocommerce_cart_loaded_from_session', 'sort_cart_items_by_sku' );
function sort_cart_items_by_sku( $cart ) {
$items_to_sort = $cart_contents = array(); // Initializing
// Loop through cart items
foreach ( $cart->cart_contents as $item_key => $item ) {
$items_to_sort[$item_key] = $item['data']->get_sku();
}
asort($items_to_sort); // sort items by sku
// Loop through sorted items key
foreach ( $items_to_sort as $key => $sku ) {
$cart_contents[$key] = $cart->cart_contents[$key];
}
WC()->cart->cart_contents = $cart_contents; // Set sorted items as cart contents
}
代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并工作。