php - WordPress doesn't read if my checkbox is checked
I need to add an additional product to the cart. I have differents options to choose so I asign one checkbox to everyone of them. Then, depends the checkbox clicked it should add the right product to the cart. The problem begans when in my function it's not detected if the checkbox is checked, I have an if() but always returns the 'else'. It should add the additional product if the checkbox is checked but it does not. The code to add the product works correctly
add_action('woocommerce_add_to_cart', 'custom_add_to_cart');
function custom_add_to_cart() {
$id = get_the_ID();
if($id = '147430'){
global $woocommerce;
$product_id_mes = 147054;
$product_id_anual = 147295;
$found = false;
if(isset($_POST['checkmes']) && $_POST['checkmes'] == 'Si'){
//check if product already in cart
if ( sizeof( WC()->cart->get_cart() ) > 0 ) {
foreach ( WC()->cart->get_cart() as $cart_item_key => $values ) {
$_product = $values['data'];
if ( $_product->id == $product_id_mes )
$found = true;
}
// if product not found, add it
if ( ! $found )
WC()->cart->add_to_cart( $product_id_mes );
} else {
// if no products in cart, add it
WC()->cart->add_to_cart( $product_id_mes );
}
} else{
//if 'checkmes' isn't checked don't add the additional product
}
}
}
Answer
Solution:
There are 2 problems in your code:
if($id = '147430')
here you're doing the assignment. you need to use==
loose comparison or===
strict comparison.- You should not use the
get_the_ID()
function for getting the product ID, you need to use 2nd param of action which is$product_id
Other suggestions:
global $woocommerce;
line if not required to add since you're using theWC()
function not the global$woocommerce
object.- use
count()
instead ofsizeof
function.