I am trying to call the function woocommerce_custom_surcharge. I need to call it within the filter for woocommerce_checkout_fields, as I need $fields[‘billing’][‘forhandler_kode’] in my IF statement, and I don’t know how to use it outside the filter. Furthermore, I have tried add_action outside the function, and it works fine there.
My echo is being called, meaning the if statement returns true, so that’s not the issue. For some reason, add_action does not work within my function
add_filter( 'woocommerce_checkout_fields' , 'call_my_add_action' );
function call_my_add_action($fields) {
if ($fields['billing']['forhandler_kode']) {
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
echo "I am being called";
}
return $fields;
}
function woocommerce_custom_surcharge() {
global $woocommerce;
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
return;
}
$percentage = -0.1;
$surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total ) * $percentage;
$woocommerce->cart->add_fee( 'Forhandlerkode Rabat', $surcharge, true, '' );
}
My question is NOT woocommerce specific, as the solution of it can help with a more general understanding of actions and filters. Thank you in advance for any help you can provide!
EDIT:
Perhaps a somewhat hacky solution to this problem (I ended up doing something entirely different so I don’t have the problem anymore, but someone might find this so here goes):
If you HAVE to have an hook fired again, without changing when it is called or using jQuery, you can simply use do_action
With my code above, I got the hook to fire again like so:
if ($fields['billing']['forhandler_kode']) {
add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' );
do_action('woocommerce_cart_calculate_fees');
echo "I am being called";
}
HOWEVER, PLEASE NOTE
This works, but it is, as Otto pointed out, a silly way to do it. A better solution is simply calling the function like so:
if ($fields['billing']['forhandler_kode']) {
woocommerce_custom_surcharge();
echo "I am being called";
}