【问题标题】:Sort WooCommerce cart by category按类别对 WooCommerce 购物车进行排序
【发布时间】:2021-05-10 21:54:16
【问题描述】:

我已经找到了一个可以按字母顺序对结帐车进行排序的 sn-p。这很完美,但如前所述,我尝试按类别对产品进行排序和分组。

有没有人可以调整以下 sn-p 以便按类别对产品进行排序?

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;
    
}

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    为了按类别对购物车商品进行分组,请添加以下代码 sn-p -

    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' );
    

    【讨论】:

    • 非常感谢!这很完美。排序的原因是,我们想以按类别排序的方式挑选我们商店中的物品而我认为订单确认邮件也会自动按类别排序,当购物车将按类别排序时。您是否也有按类别对确认邮件进行排序的 sn-p?
    【解决方案2】:

    您应该能够使用类WC_Product 中定义的方法get_category_ids() 访问类别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 获得第一个。此外,如果同一类别中有多个产品,这没有额外的排序逻辑.

    请注意,这是未经测试的,只是关于如何处理此问题的方法的想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 2021-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多