Ad
Count Custom Taxonomy Terms In WooCommerce Cart And Multiply The Cart Total By The Number
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!
Ad
Answer
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 );
Ad
source: stackoverflow.com
Related Questions
- → CORS missmatch because of http
- → Building sitemap for 2 wordpress install under 1 domain
- → How to remove empty elements after class?(jQuery)
- → Get width of an element and apply to another relative to the first one?
- → How to remove caption p class from wordpress?
- → 301 Redirection from no-www to www in wordpress
- → Laravel 5 routing using prefix
- → WordPress - Header position Top, Left &Right
- → how to add rel=nofollow to some specific external links in wordpress
- → octobercms install error: database is not empty?
- → How to edit the index page of wordpress theme?
- → How to select a Post Type (Wordpress) to pass a filter in head?
- → What sort of URL structure should be used to display AMP HTML vs vanilla HTML
Ad