我已经找到一个片段,用于按字母顺序对结帐购物车进行排序。效果很好,但如上所述,我尝试按类别对产品进行分类和分组。
有人可以调整以下代码片段,以便按类别对产品进行排序吗?
add_action( 'woocommerce_cart_loaded_from_session', 'bbloomer_sort_cart_items_alphabetically' );
function bbloomer_sort_cart_items_alphabetically() {
global $woocommerce;
// READ CART ITEMS
$products_in_cart = array();
foreach ( $woocommerce->cart->cart_contents as $key => $item ) {
$products_in_cart[ $key ] = $item['data']->get_title();
}
// 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 ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}
答案 0 :(得分:0)
您应该能够使用类get_category_ids()
中定义的方法WC_Product
访问类别ID
$item['data']->get_category_ids()
但这会给您返回array
,因此您需要处理获取ID的问题,例如
$ids = $item['data']->get_category_ids();
$id = $ids[ 0 ];
并转换为字符串,例如
$term_obj = get_term( $id, 'product_cat' );
$name = $term_obj->name;
然后您可以做
$products_in_cart[ $key ] = $name;
并按照问题代码中使用的相同逻辑,按类别排序。
尽管有几件事情要考虑,但它不能处理多个类别中的商品,它只能通过使用索引0来获得第一个。此外,如果同一类别中有多个产品,则没有额外的排序逻辑
请注意,这未经测试,仅是如何处理此问题的想法。
答案 1 :(得分:0)
为了按类别对购物车项目进行分组,请添加以下代码段-
function woocommerce_before_cart_contents(){
global $woocommerce;
$cat_wisw_pros = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id = $cart_item['product_id'];
$cat_ids = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
foreach ( $cat_ids as $id ) {
$cat_wisw_pros[$id][$cart_item_key] = $cart_item;
}
}
ksort( $cat_wisw_pros ); // Cat ID wise sort
$grouped_cart_items = array();
foreach ( $cat_wisw_pros as $cat_id => $cart_items ) {
foreach ( $cart_items as $cart_item_key => $cart_item ) {
if( !array_key_exists( $cart_item_key, $grouped_cart_items ) )
$grouped_cart_items[$cart_item_key] = $cart_item;
}
}
$woocommerce->cart->cart_contents = $grouped_cart_items;
}
add_action( 'woocommerce_before_cart_contents', 'woocommerce_before_cart_contents' );