Woocommerce按产品类别分类推车产品

时间:2015-09-13 10:50:18

标签: wordpress woocommerce

问题

我想这样做,所以我的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' );

1 个答案:

答案 0 :(得分:3)

你已经拥有了所有合适的作品。

要在此上下文中获取帖子条款,您需要调整如何获取购物车项目的ID $terms = wp_get_post_terms($item['data']->id, 'product_cat' );

获取帖子术语的结果将为您提供一个看起来像这样的数组

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 );
相关问题