Last Updated: July 16, 2021
·
695
· Mad Scientist

How to use Superglobal array $_SESSION along with a function wp_mail

Let's look at a simple way to work with session variables in PHP

Let's go in order

1 First, you need to initialize the session using the session_start () function; and the wp-load file

session_start();
require_once '../../../wp-load.php';

2 Next, we need to save the session variable using the setcookie function. In which we pass the name of the variable, and the lifetime of the cookie.

ob_start();
    setcookie('text', $_POST['text'], time()+60 );
ob_flush();
$_SESSION['text']=$_POST['text'];

3 After the data has been saved, we can send using the wp_mail function


$text_to_mail = $_SESSION['text'];  
if($text_to_mail = trim(htmlspecialchars($_POST['text']))){
$message .= 
'Comment:'.$text_to_mail ;
}

$mail_to = "example@gmail.com";
$email_subject = "$_SESSION+wp_mail";
if (wp_mail($mail_to, $email_subject, $message)){
//Destroy session after send
session_unset();
session_destroy(); 
}

_Full source code on Github Gist:_