Skip to content

Instantly share code, notes, and snippets.

@reggieofarrell
Last active March 29, 2023 14:50
Show Gist options
  • Save reggieofarrell/b41bc9c3ea2dc70b0236767d42e0fc6c to your computer and use it in GitHub Desktop.
Save reggieofarrell/b41bc9c3ea2dc70b0236767d42e0fc6c to your computer and use it in GitHub Desktop.
Default MailPoet opt-in to checked on WooCommerce / Cartflows checkout pages
<?php
/**
* Defaults the MailPoet opt-in checkbox on the WooCommerce and/or
* Cartflows checkout pages to a checked state. Also properly handles
* the checkbox when 'update_checkout' events are fired.
*
* This code could either be placed in the functions.php of the active theme,
* a custom plugin, or be injected via plugins like WP Code or Code Snippets
*/
add_action('wp_footer', function() {
if ( function_exists('is_checkout') && is_checkout() ) {
ob_start(); ?>
<script type="text/javascript" id="default-checkout-optin-true">
(function($) {
let isFirstRun = true;
let wasAlreadyChecked = false;
function checkTheBox() {
document.getElementById("mailpoet_woocommerce_checkout_optin").checked = true;
}
function getTheCheckboxValue() {
return document.getElementById("mailpoet_woocommerce_checkout_optin").checked;
}
/**
* this event fires after the ajax request from 'update_checkout' is complete
* and the checkout pages has been updated
*/
$(document).on('updated_checkout', function() {
/**
* this is the inital checkout load, check the box
*/
if (isFirstRun) {
checkTheBox();
isFirstRun = false;
wasAlreadyChecked = true;
}
/**
* not the first 'update_checkout' cycle, persist the
* checkbox state if it was already checked before the
* event was fired
*/
else if (!isFirstRun && wasAlreadyChecked) {
checkTheBox();
}
});
/**
* update_checkout event is fired when anything changes
* on the checkout page that would cause possible cart
* recalculations.
*/
$(document).on('update_checkout', function() {
/**
* if the event fired and it's NOT the first run,
* set wasAlreadyChecked to the current checkbox value.
* This is so that if the user manually unchecked the box
* our 'updated_checkout' event listener above won't re-check
* it
*/
if (!isFirstRun) {
wasAlreadyChecked = getTheCheckboxValue();
}
});
})(jQuery);
</script>
<?php echo ob_get_clean();
}
}, 999999); // high priority number to ensure this injected into the footer after jQuery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment