Inviare e-mail da WordPress è un tipico esempio di come automatizzare i task tramite l'OOP.
La classe che andremo a definire semplifica l'invio delle e-mail permettendo di gestire l'intero processo:
class My_Email {
public $to;
public $subject;
public $message;
protected $_from;
public function __construct( $to, $subject, $message ) {
$this->to = $to;
$this->subject = $subject;
$this->message = $this->setMessage( $message );
}
// Il campo From potrebbe non essere sempre lo stesso
public function setFrom( $from, $fromName ) {
$this->_from = 'From: ' . $fromName . ' <' . $from . '>' . "\r\n";
}
// Il messaggio potrebbe essere su più righe
public function setMessage( $msg ) {
$text = "";
if( is_array( $msg ) ) {
foreach( $msg as $k => $v ) {
$text .= $k . ": " . $v . "\n\n";
}
} else {
$text = $msg;
}
return $text;
}
public function send() {
return wp_mail( $this->to, $this->subject, $this->message, $this->_from );
}
}
Esempio d'uso durante la registrazione di un nuovo utente:
require_once( 'My_Email.php' );
function my_register_user() {
$username = trim( $_POST['my-username'] );
$email = trim( $_POST['my-email'] );
$password = trim( $_POST['my-password'] );
// Se la validazione ha avuto successo:
$message = array(
'Username' => $username,
'Password' => $password
);
$my_email = new My_Email( $email, 'I tuoi dati di accesso', $message );
$my_email->setFrom( 'noreply@miosito.it', get_bloginfo( 'name' ) );
if( $my_email->send() ) {
// Messaggio di avvenuto invio
}
}