How to insert a discount when choosing the shipping method "local pickup"?

add_action( 'woocommerce_cart_calculate_fees', 'custom_discount_for_pickup_shipping_method', 10, 1 );
function custom_discount_for_pickup_shipping_method( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $percentage = 5; // Rabatt in %

    $chosen_shipping_method_id = WC()->session->get( 'chosen_shipping_methods' )[0];
    $chosen_shipping_method    = explode(':', $chosen_shipping_method_id)[0];

    if ( strpos( $chosen_shipping_method_id, 'local_pickup' ) !== false ) {
        $discount = $cart->get_subtotal() * $percentage / 100;
        $cart->add_fee( __('Rabatt') . ' (' . $percentage . '%)', -$discount );
    }
}
Without cookies
This website does not use cookies or tracking. More information can be found in the privacy policy.