Search code examples
javascriptphpwordpresswoocommercewoocommerce-subscriptions

WooCommerce change checkbox value based on product in cart


We use a plugin for the payment gateways. There is a setting for recurring subscriptions. Now we have a subscription where we need that checkbox selected and we have one sub where we don't need that recurring checkbox.

This is the original plugin code:

<input type="checkbox" checked name="payrexx-allow-recurring" id="payrexx-allow-recurring" value="1" />

Now, if the special subscription (check with ID) is in the cart, then uncheck the checkbox and hide the checkbox. If another sub is in the cart, do nothing.

Can we do this with PHP or is here js needed? I'm a beginner, so would be nice if you guys can tell me how I can do this and how. :)

Cheers and Thanks


Solution

  • function conditional_checkout_fields_js( $fields ) {
        $cart = WC()->cart->get_cart();
    
        foreach ( $cart as $item_key => $values ) {
            $product = $values['data'];
    
            if ( $product->get_id() == 1631817356 ) { // Change the product ID
                   $html .= '<script type="text/javascript">
                      jQuery(function() {
                        jQuery("#payrexx-allow-recurring").prop("checked", false); // Unchecks it
                        jQuery("#payrexx-allow-recurring").hide();
                      });
                    </script>';
                   echo $html;
            }
        }
    
        return $fields;
    }
    add_filter( 'woocommerce_checkout_fields', 'conditional_checkout_fields_js' );
    

    Add this to your active child theme functions.php file