Woocommerce sort cart products by product category
问题
我想让我的 Woocommerce 购物车按产品类别的顺序显示产品。 (我的产品被分配给一个品牌,我希望这些产品出现在他们指定品牌下的购物车区域。)
我尝试过的
目前,我已经能够让它按字母顺序按键排序,但这就是我对数组的了解。
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | add_action( 'woocommerce_cart_loaded_from_session', function() { global $woocommerce; $products_in_cart = array(); foreach ( $woocommerce->cart->cart_contents as $key => $item ) { $products_in_cart[ $key ] = $item['data']->get_title(); } ksort( $products_in_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; }, 100 ); |
附加说明
我知道我可以使用此代码来获取每个产品的术语 ID。但我不太确定如何最好地构建我的代码以获得我想要的结果。
1 | $terms = wp_get_post_terms(get_the_ID(), 'product_cat' ); |
你已经得到了所有正确的部分。
要在这种情况下获取帖子条款,您需要调整获取购物车项目 ID 的方式
获取post terms的结果会给你一个看起来像这样的数组
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | Array( [0] => stdClass Object( [term_id] => 877 [name] => Product Category Name [slug] => Product Category Name [term_group] => 0 [term_taxonomy_id] => 714 [taxonomy] => product_cat [description] => [parent] => 0 [count] => 1 [filter] => raw ) ) |
下面的代码将按照数组中的第一个类别对购物车进行排序。这还不完整,您需要考虑未设置产品类别以及设置多个产品类别。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | add_action( 'woocommerce_cart_loaded_from_session', function() { global $woocommerce; $products_in_cart = array(); foreach ( $woocommerce->cart->cart_contents as $key => $item ) { $terms = wp_get_post_terms($item['data']->id, 'product_cat' ); $products_in_cart[ $key ] = $terms[0]->name; } ksort( $products_in_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; }, 100 ); |