Note: In your code the $cart
argument is missing from the hooked function and it's an action hook, but not a filter hook.
The WC_Cart
method add_fee()
doesn't allow to add custom meta data, so you will need to add it before on add_to_cart event or in WC_Session
.
You can add custom meta data to WC_Order_Item_Fee
when order is submitted using the following code example (using WC_Session to set and get the custom meta data in here):
// Add a custom cart fee
add_action( 'woocommerce_cart_calculate_fees', 'adding_cart_fees', 10, 1 );
function adding_cart_fees( $cart ){
$cart->add_fee(__("Added fee"), 10, true, '');
}
// Set Fee custom meta data in WC_Session
add_action( 'woocommerce_calculate_totals', 'calculate_totals_for_fees_meta_data', 10, 1 );
function calculate_totals_for_fees_meta_data( $cart ){
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return;
$fees_meta = WC()->session->get('fees_meta');
$update = false;
// Loop through applied fees
foreach( $cart->get_fees() as $fee_key => $fee ) {
// Set the fee in the fee custom meta data array
if( ! isset($fees_meta[$fee_key]) ){
$fees_meta[$fee_key] = 'some value';
$update = true;
}
}
// If any fee meta data doesn't exist yet, we update the WC_Session custom meta data array
if ( $update ) {
WC()->session->set('fees_meta', $fees_meta);
}
}
// Save fee custom meta data to WC_Order_Item_Fee.
add_action( 'woocommerce_checkout_create_order_fee_item', 'save_custom_met_data_to_fee_order_items', 10, 4 );
function save_custom_met_data_to_fee_order_items( $item, $fee_key, $fee, $order ) {
// Get fee meta data from WC_Session
$fees_meta = WC()->session->get('fees_meta');
// If fee custom meta data exist, save it to fee order item
if ( isset($fees_meta[$fee_key]) ) {
$item->update_meta_data( 'custom_key', $fees_meta[$fee_key] );
}
}
// Remove Fee meta data from WC_Session.
add_action( 'woocommerce_checkout_create_order', 'remove_fee_custom_met_data_from_wc_session', 10, 2 );
function remove_fee_custom_met_data_from_wc_session( $order, $data ) {
$fees_meta = WC()->session->__unset('fees_meta');
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
The custom meta data is saved to WC_Order_Item_Fee and you can get it using something like:
// Get an instance of the WC_Order Object (if needed)
$order = wc_get_order( $order_id );
// loop through fee order items
foreach ( $order->get_items('fee') as $fee_key => $item ) {
// Get the fee custom meta data
$fee_custom_meta = $item->get_meta('custom_key');
if ( $fee_custom_meta ) {
// Display the custom meta data value
echo '<p>' . $fee_custom_meta . '</p>';
}
}