Kane
Kane

Reputation: 615

Showing technical difficulties if using add_to_cart() function

I have added this code for a custom checkbox product. But after clicking the checkbox and when we click the add to cart button then this error is showing. The site is experiencing technical difficulties. How can I overcome this?

add_action( 'woocommerce_before_add_to_cart_button', 'custom_product_option_checkbox_field' );
function custom_product_option_checkbox_field() {
    if (isset( $_POST['option1']) && $_POST['option1'] != '') {
        echo '<p><label><input type="checkbox" id="option1" name="option1" value="certificate" checked> '.__("Add PDF Certificate at <span>&#163;9.99</span>").'</label></p>';
    }else{
        echo '<p><label><input type="checkbox" id="option1" name="option1" value="certificate" > '.__("Add PDF Certificate at <span>&#163;9.99</span>").'</label></p>';
    }
}


add_action('woocommerce_add_to_cart', 'custome_add_to_cart');
function custome_add_to_cart() {
    global $woocommerce;
    echo $_POST['option1'];
    if ($_POST['option1']) {
            $product_id = 2218;         
            WC()->cart->add_to_cart( $product_id );
    }
}

Upvotes: 0

Views: 484

Answers (1)

Kradyy
Kradyy

Reputation: 345

By inserting a new product using WC()->cart->add_to_cart in the action woocommerce_add_to_cart function it creates a indefinite recursive loop which throws the error.

We can fix this by removing the add_to_cart action before inserting the new product:

remove_action('woocommerce_add_to_cart', __FUNCTION__);

Updated code:

    add_action('woocommerce_add_to_cart', 'custome_add_to_cart');

    function custome_add_to_cart() {
        if (isset($_POST['option1'])) {
            $product_id = 2218;

            // Prevent the add_to_cart action from looping
            remove_action('woocommerce_add_to_cart', __FUNCTION__);

            WC()->cart->add_to_cart( $product_id );
        }
    }

Upvotes: 3

Related Questions