Skip to content

Instantly share code, notes, and snippets.

@elclanrs
Last active July 26, 2024 06:10
Show Gist options
  • Save elclanrs/6516451 to your computer and use it in GitHub Desktop.
Save elclanrs/6516451 to your computer and use it in GitHub Desktop.
Simple e-mail confirmation plugin for WordPress.

Email Confirmation for WordPress

Send an email to the user with confirmation code and store form data in database until user confirms.

Requires: PHP 5.3+

How To

Installation

Drop the plugin in /wp-content/plugins/email-confirmation and activate in WordPress.

Usage

Make sure to validate all your data before using Email Confirmation, then you can call the plugin anywhere in your templates:

<?php
$headers = 'From: admin <noreply@admin>';
$to = $_POST['email'];
$subject = 'Confirm';
// The unique token can be inserted in the message with %s
$message = 'Thank you. Please <a href="<?= home_url('confirm') ?>?token=%s">confirm</a> to continue';

if ($isAllValid) {
  EmailConfirmation::send($to, $subject, $message, $headers);
}

The above will send an email with a unique token for confirmation and store the $_POST array in the DB.

The confirmation link can be any page or template you want. For a minimal setup all you need is to pass the token in $_GET. The check method will retrieve the data for a specific token and return it, then remove it from the DB. If the token doesn't exist it will return null.

<?php
$data = EmailConfirmation::check($_GET['token')); // $_POST saved for this token
<?php
/**
* Plugin Name: Email Confirmation
* Description: Send an email to the user with confirmation code and store form data in database until user confirms.
* Author: Cedric Ruiz
*/
class EmailConfirmation
{
const PREFIX = 'email-confirmation-';
public static function send($to, $subject, $message, $headers)
{
$token = sha1(uniqid());
$oldData = get_option(self::PREFIX .'data') ?: array();
$data = array();
$data[$token] = $_POST;
update_option(self::PREFIX .'data', array_merge($oldData, $data));
wp_mail($to, $subject, sprintf($message, $token), $headers);
}
public static function check($token)
{
$data = get_option(self::PREFIX .'data');
$userData = $data[$token];
if (isset($userData)) {
unset($data[$token]);
update_option(self::PREFIX .'data', $data);
}
return $userData;
}
}
@linrogerson
Copy link

How do I input the confirmation link in my site page ?

@ejntaylor
Copy link

fyi: $data = EmailConfirmation::check($_GET['token']); // $_POST saved for this token

typo ] instead of )

@abdelhak-ajbouni
Copy link

I really don't get how this works !

@Naveendubey93
Copy link

hello I want to send the mail confirmation and cancel link by submitting forms without any plugin,only custom code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment