php – WooCommerce add optional product to cart

I give my user the option to add a subscription product to the cart by selecting a radio button. If the user removes the parent product, I remove the subscription product from the cart.

The code runs when a product is added to the cart and when a product is removed from the cart.

I’d like to get some feedback on the code I am using to detect add to cart / remove from cart functionality.

// Output the Custom field in Product pages
add_action("woocommerce_before_add_to_cart_button", "options_on_single_product", 1);
function options_on_single_product(){
    ?>
        <label>
            <input type="radio" name="subscription_product" checked="checked" value="277">6mos.
            <span></span>
        </label>
        <label>
            <input type="radio" name="subscription_product" value="278">9mos.
            <span></span>
        </label>
        <label>
            <input type="radio" name="subscription_product" value="279">12mos.
            <span></span>
        </label>
    <?php
}

add_action( 'woocommerce_before_calculate_totals', 'add_remove_subscription', 50, 1 );
function add_remove_subscription( $cart ) {

    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    if ( did_action( 'woocommerce_before_calculate_totals' ) >= 2 )
        return;
    
    $subscription_id = '';
    $has_others = false;

    if( isset( $_REQUEST('subscription_product') ) ) {
        $subscription_id = $_REQUEST('subscription_product'); 
    } else {
        $subscription_id = (277,278,279); 
    }

    // Loop through cart items
    foreach( $cart->get_cart() as $cart_item_key => $cart_item ) {
        $product_id = $cart_item('data')->get_id();
        
        if ( in_array($product_id, $subscription_id) || $product_id == $subscription_id ) {
            // Subscription product is in cart
            $subscription_key = $cart_item_key;
        } else {
            // Other items are in cart
            $has_others = true;
        }
    }
    // If subscription product is alone in cart we remove it
    if( ! $has_others && isset( $subscription_key ) ){
        $cart->remove_cart_item( $subscription_key );
    } elseif ( $has_others && ! isset( $subscription_key ) ) {
        $cart->add_to_cart($subscription_id);
    }
}