Ad
Add The Values Of Product Meta As Fee In WooCommerce Cart
In Italy there is a specific fee for the disposal of electronic products that must be paid during the purchase.
This "ecofee" is specific for each product.
I have set up a specific meta for each product called meta_product_grossecofee
I'd like to convert the value of this meta field in a fee on the cart.
This is the code I've tried, however without the desired result. Any advice?
add_action( 'woocommerce_cart_calculate_fees', 'ecofee_display' );
function ecofee_display(){
global $product;
$ecofee = $product->get_meta('meta_product_grossecofee');
if ($ecofee) {
WC()->cart->add_fee(__('Ecofee: ', 'txtdomain'), $ecofee);
}
}
Ad
Answer
The cart can contain multiple products, so global $product
is not applicable here.
Instead, you can go through the cart and for each product for which the meta exists, add the value for this to the fee.
If the $fee is greater than 0, you can then apply it.
So you get:
function action_woocommerce_cart_calculate_fees( $cart ) {
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
// Initialize
$fee = 0;
// Loop through cart contents
foreach ( $cart->get_cart_contents() as $cart_item ) {
// Get meta
$ecofee = $cart_item['data']->get_meta( 'meta_product_grossecofee', true );
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Addition
$fee += $ecofee;
}
}
// If greater than 0
if ( $fee > 0 ) {
// Add additional fee (total)
$cart->add_fee( __( 'Ecofee', 'woocommerce' ), $fee, false );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'action_woocommerce_cart_calculate_fees', 10, 1 );
Note: if you want to take into account the quantity per product:
Replace
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Addition
$fee += $ecofee;
}
With
// NOT empty & variable is a number
if ( ! empty ( $ecofee ) && is_numeric( $ecofee ) ) {
// Get product quantity in cart
$quantity = $cart_item['quantity'];
// Addition
$fee += $ecofee * $quantity;
}
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