Used Chat GPT to write me a Snippet for our Woocommerce checkout page, would anyone please tell me if it’s safe to use.

[ad_1]

The snippet’s purpose is to add a checkbox on the checkout page so the client can subscribe to our newsletter, if he checks it we get an email with the clients email confirming they want to subscribe, if they don’t, we don’t get anything. Pretty simple.

After asking chat-GPT and having a back and forth I got this:

/**
* Add newsletter subscription checkbox to WooCommerce checkout
*/
function add_newsletter_subscription_checkbox() {
woocommerce_form_field( ‘newsletter_subscription’, array(
‘type’ => ‘checkbox’,
‘class’ => array(‘form-row-wide’),
‘label’ => __(‘Subscribe to our newsletter?’, ‘Our company name’),
‘default’ => 0, // Set the default value to 0 (unchecked)
), false ); // Set the current value to false
}

add_action( ‘woocommerce_after_checkout_billing_form’, ‘add_newsletter_subscription_checkbox’ );

/**
* Send newsletter subscription preference via email
*/
function send_newsletter_subscription_preference( $order_id ) {
$order = wc_get_order( $order_id );

// Check if the checkbox is checked
$subscription_preference = isset( $_POST[‘newsletter_subscription’] ) && $_POST[‘newsletter_subscription’] === ‘1’ ? ‘Yes’ : ‘No’;

// Get the customer’s email address from the order and sanitize it
$customer_email = $order->get_billing_email();
$customer_email = is_email( $customer_email ) ? sanitize_email( $customer_email ) : ”;

// Validate the checkbox value and email address
if ( $subscription_preference === ‘Yes’ && ! empty( $customer_email ) ) {
$email_subject = ‘Newsletter Subscription Preference’;
$email_content = ‘Newsletter Subscription Preference: ‘ . $subscription_preference . “\n”;
$email_content .= ‘Customer Email: ‘ . $customer_email;

wp_mail( ‘[email protected]’, $email_subject, $email_content );
}
}

add_action( ‘woocommerce_checkout_order_processed’, ‘send_newsletter_subscription_preference’ );

I’ve been testing it on our Staging site and it seems to work.

But, is it right and safe?

[ad_2]
4 Comments
  1. Just make sure you add your snippet from the backend and not through a file manager plugin. If you crash the site, you’ll need to remove the code.

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer