Home > Net >  Count custom taxonomy terms in WooCommerce cart and multiply the cart total by the number
Count custom taxonomy terms in WooCommerce cart and multiply the cart total by the number

Time:10-15

I have a custom taxonomy for WooCommerce products, let's say the slug is city.

The goal of the code is to loop through the cart contents, and save the number of unique city taxonomy entries.

After that, the original price needs to be multiplied by the number of the counted all unique city taxonomies.

I managed to get to this code where it gets the taxonomy terms, but oblivious on what to do next:

foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) {
$product_id   = $cart_item['product_id'];
$term_names = wp_get_post_terms( $product_id, 'city', array('fields' => 'names') );}

Any advice would be greatly appreciated!

CodePudding user response:

To change the cart total you can use the woocommerce_calculated_total filter hook

Then you can use count(), which counts all elements in the array $term_names and add the result to the $counter variable

So you get:

function filter_woocommerce_calculated_total( $total, $cart ) {
    // Initialize
    $counter = 0;
    
    // Iterating though each cart items
    foreach ( $cart->get_cart() as $cart_item_key => $cart_item ) {
        // Product ID in cart
        $product_id = $cart_item['product_id'];

        // Get terms
        $term_names = wp_get_post_terms( $product_id, 'city', array( 'fields' => 'names' ) );
        
        // Add to counter
        $counter  = count( $term_names );
    }

    return $total * $counter;
}
add_filter( 'woocommerce_calculated_total', 'filter_woocommerce_calculated_total', 10, 2 );
  • Related