Joh*_*nes 8 wordpress woocommerce
嗨,我们正在尝试按主要产品类别对 Woo Cart 进行排序,并在该类别中的产品下列出。像下面这样:
车轮零件
框架
座位
我们已经设法按猫顺序显示,但它没有将它们排序到 Main Cat -> Sub Cat
我们有以下代码并尝试按 cat 和 sub cat 订购购物车数组
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;
}
natsort( $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 );
Run Code Online (Sandbox Code Playgroud)
任何人有任何想法吗?
您的代码是正确的,但您只是natsort返回 1 导致了问题。您还需要按菜单顺序对类别进行排序。请检查下面的代码是否正常工作。
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]->term_id;
}
// $categories = get_terms( 'product_cat', 'orderby=menu_order&hide_empty=1' );
asort($products_in_cart);
$cat_array = array();
foreach ($products_in_cart as $key => $value) {
$cat_array[$key] =get_term_by('id', $value, 'product_cat');
}
$mai_cat = [];
$i=0;
foreach ($cat_array as $parent_key => $parent_value) {
if($parent_value->parent == 0)
{
$mai_cat[$parent_key] = $parent_value->term_id;
foreach ($cat_array as $parent_key_sub => $parent_value_sub) {
if($parent_value_sub->parent == $parent_value->term_id)
{
$mai_cat[$parent_key_sub] = $parent_value_sub->term_id;
}
}
}
}
$cart_contents = array();
foreach ( $mai_cat as $cart_key => $product_title ) {
$cart_contents[ $cart_key ] = $woocommerce->cart->cart_contents[ $cart_key ];
}
$woocommerce->cart->cart_contents = $cart_contents;
}, 100 );
Run Code Online (Sandbox Code Playgroud)
经过测试并且运行良好
| 归档时间: |
|
| 查看次数: |
367 次 |
| 最近记录: |