Woocommerce sort cart products by product category

▼魔方 西西 提交于 2021-02-18 08:46:40

问题


The Problem

I would like to make it so my Woocommerce cart shows products in order of product category. (My products are assigned to a brand, and i want the products to appear in the cart area under their assigned brands.)

What I have tried

At the moment i've been able to get it to sort alphabetical by key however this is as far as my knowledge with arrays goes.

Example Code

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

Additional Notes

I know I can use this code to get the term ID of each product. But i'm not quite sure how best to structure my code to get the outcome I'm after.

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

回答1:


You've got all the right pieces.

To get the post terms in this context you need to tweak how you are getting the ID of the cart item $terms = wp_get_post_terms($item['data']->id, 'product_cat' );

The result of getting the post terms will give you an array that looks like this

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

The code below will sort the cart by the first category in the array. This is not complete, you will need to account for no product category being set and also multiple product categories being set.

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


来源:https://stackoverflow.com/questions/32548889/woocommerce-sort-cart-products-by-product-category

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!