简体   繁体   中英

Get the product category terms from cart items in WooCommerce

I only get the product category on some producs, on some I don't

function savings_33_55_cart() {
    foreach ( WC()->cart->get_cart() as $key => $cart_item ) { 
        for ($i=0; $i < $cart_item['quantity'] ; $i++) {   
            $productId = $cart_item['data']->get_id();

            echo "PROD ID: " . $productId . "<br>";

            $terms = get_the_terms( $productId, 'product_cat' );

            foreach ($terms as $term) {
                $product_cat = $term->name;
                echo "PRODUCT CATEGORY: " . $product_cat . "<br>"; 
            }
        }
    }
}

add_action( 'woocommerce_cart_totals_before_order_total', 'savings_33_55_cart' );

I expect to get a product category on every product, but I only get the product category on some products

First your $product_cat variable is not defined.

To get a product category on cart items , you need to get the parent variable product ID for product variations as they don't handle custom taxonomies as product categories or product tags.

To get the correct product ID for any custom taxonomy terms on cart items always use :

 $product_id = $cart_item['product_id'];

Instead of:

 $product_id = $cart_item['data']->get_id();


Now if you need to get the product category term names , instead of using get_the_terms() function, you can use wp_get_post_terms() and implode() functions like:

$term_names = wp_get_post_terms( $product_id, 'product_cat', ['fields' => 'names'] );

// Displaying term names in a coma separated string
if( count( $term_names ) > 0 )
    echo __("Product categories") . ": " . implode( ", ", $term_names ) . '<br>':

// OR displaying term names as a vertical list
if( count( $term_names ) > 0 )
    echo __("Product categories") . ": " . implode( "<br>", $term_names ) . '<br>';


So in a cart items foreach loop:

// Loop through cart items
foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
    $quantity     = $cart_item['quantity']; 
    $product_id   = $cart_item['product_id'];
    $variation_id = $cart_item['variation_id'];

    echo __("PRODUCT ID: ") . $product_id . "<br>";

    $term_names = wp_get_post_terms( $product_id, 'product_cat', array('fields' => 'names') );

    if ( count($term_names) > 0 ) {
        echo __("PRODUCT CATEGORY: ") . implode("<br>", $term_names) . "<br>";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM