nobilik nobilik - 2 months ago 17
PHP Question

How to get sum of custom attribute values in cart?

Some of my products has custom attribute

pa_ves-g
. In cart total I need to get entire volume of all products in cart.

I found this code for weight:

function myprefix_cart_extra_info() {
global $woocommerce;
echo '<div class="cart-extra-info">';
echo '<p class="total-weight">' . __('Total weight', 'woocommerce');
echo ' ' . $woocommerce->cart->cart_contents_weight . ' ' . 'kg';
echo '</p>';
echo '</div>';
}


So how to do the same for
pa_ves-g
?

Thanks.

Answer

First you are using old (working) cart syntax: you don't need anymore global woocommerce; if instead using $woocommerce->cart you use WC()->cart actual syntax.

Use that code to get total cart volume value for volume attribute:

function myprefix_cart_extra_info() {
    $volume = 0;

    // Iterating though each item in cart
    $cart_items = WC()->cart->get_cart();
    foreach( $cart_items as $cart_item ){
        $item_id = $cart_item['product_id'];
        $terms = get_the_terms( $item_id , 'pa_ves-g');
            foreach($terms as $key => $term)
                if(!empty($term->name)) $volume += $term->name;
        }

    echo '<div class="cart-extra-info">';
    echo '<p class="total-weight">' . __('Total volume', 'woocommerce');
    echo ' ' . $volume . ' ' . 'm3';
    echo '</p>';
    echo '</div>';
}

This goes in function.php file of your active child theme (or theme) or also in any plugin file.

This code is tested and works.

Comments