Newsletter Opt-In Checkbox at Checkout
Adds an unticked "Send me news and offers" checkbox to the classic checkout and stores the customer's consent on the order and their account.
Opens WPIDE on
Code
add_action( 'woocommerce_review_order_before_submit', function () {
woocommerce_form_field( 'wpide_newsletter_optin', array(
'type' => 'checkbox',
'class' => array( 'form-row' ),
'label' => 'Send me news and offers by email. You can unsubscribe at any time.',
) );
}, 5 );
add_action( 'woocommerce_checkout_create_order', function ( $order ) {
if ( empty( $_POST['wpide_newsletter_optin'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
$order->update_meta_data( '_wpide_newsletter_optin', current_time( 'mysql' ) );
if ( $order->get_customer_id() ) {
update_user_meta( $order->get_customer_id(), 'wpide_newsletter_optin', current_time( 'mysql' ) );
}
} );
add_action( 'woocommerce_admin_order_data_after_billing_address', function ( $order ) {
$date = $order->get_meta( '_wpide_newsletter_optin' );
echo '<p><strong>Newsletter:</strong> ' . ( $date ? esc_html( 'Opted in on ' . $date ) : esc_html( 'No' ) ) . '</p>';
} );
Notes
Consent is saved as order meta _wpide_newsletter_optin and user meta wpide_newsletter_optin. Connect it to your email tool with an export or integration.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.