【问题标题】:Woocommerce sort cart products by product categoryWoocommerce 按产品类别对购物车产品进行排序
【发布时间】:2015-12-09 12:22:22
【问题描述】:

问题

我想让我的 Woocommerce 购物车按产品类别的顺序显示产品。 (我的产品被分配给一个品牌,我希望这些产品出现在他们指定品牌下的购物车区域。)

我的尝试

目前我已经能够让它按字母顺序按键排序,但这就是我对数组的了解。

示例代码

    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。但我不太确定如何最好地构建我的代码以获得我想要的结果。

  $terms = wp_get_post_terms(get_the_ID(), 'product_cat' );

【问题讨论】:

    标签: wordpress woocommerce


    【解决方案1】:

    你得到了所有正确的部分。

    要在这种情况下获取帖子条款,您需要调整获取购物车项目 ID 的方式 $terms = wp_get_post_terms($item['data']->id, 'product_cat' );

    获取post terms的结果会给你一个看起来像这样的数组

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

    下面的代码将按照数组中的第一个类别对购物车进行排序。这还不完整,您需要考虑未设置产品类别以及设置多个产品类别。

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

    【讨论】:

    • 你有解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    相关资源
    最近更新 更多