Reputation: 549
I have a WooCommerce site that has a couple of products that have been getting a lot of returns due to them ordering the wrong thing. I have added a "Cheat Sheet" that the customer can reference via Advanced Custom Fields. I have written the below code to force them to check the box to acknowledge that they have read it before they can add the product to the cart.
The problem is that no matter if they check the box or not, I get the custom error message displayed. So obviously I have a flaw in my logic, but I can't pinpoint it.
Any help would be greatly appreciated.
<?php
// Add Confirmation Checkbox on Product Single
add_action( 'woocommerce_single_product_summary', 'woocommerce_cheat_sheet_confirm', 29 );
function woocommerce_cheat_sheet_confirm() {
global $post;
$cheat_sheet = get_field('cheat_sheet'); // Get Advanced Custom Field
if ( ! empty( $cheat_sheet ) ) { // If it exists, add the confirmation box ?>
<div id="cheat-sheet-confirmation" class="checkbox">
<form>
<label>
<input id="cheatsheetconfirm" name="cheatsheetconfirm" type="checkbox" value="isconfirmed"> I confirm that I have read the <a href="<?php echo $cheat_sheet['url']; ?>" />cheat sheet</a>.
</label>
</form>
</div>
<?php }
}
function cheatsheetConfirmation() {
if(isset($_REQUEST['cheatsheetconfirm']) && $_REQUEST['cheatsheetconfirm'] == 'on'){
$is_checked = true;
}
else {
$is_checked = false;
}
if ($is_checked == false) {
wc_add_notice( __( 'Please acknowledge that you have read the cheat sheet.', 'woocommerce' ), 'error' );
return false;
}
return true;
}
add_action( 'woocommerce_add_to_cart_validation', 'cheatsheetConfirmation', 10, 3 );
Upvotes: 4
Views: 483
Reputation: 3968
The error is here.
<input id="cheatsheetconfirm" name="cheatsheetconfirm" type="checkbox" value="isconfirmed"> I confirm that I have read the <a href="<?php echo $cheat_sheet['url']; ?>">cheat sheet</a>
Change it to this
<input id="cheatsheetconfirm" name="cheatsheetconfirm" type="checkbox" value="on"> I confirm that I have read the <a href="<?php echo $cheat_sheet['url']; ?>">cheat sheet</a>
I changed the value
of the <input>
tag.
You were correct that the logic was wrong. You were checking the value of $_REQUEST['cheatsheetconfirm']
which is set to post "isconfirmed". This means that your if statement returns false since you want $_REQUEST['cheatsheetconfirm']
to equal "isconfirmed" and not "on".
If you change the value that is submitted via the form then your if statement will return true.
Upvotes: 5