Overriding Wordpress mail function wp_mail()
In one of my previous projects i was instructed to override Wordpress function wp_mail() with custom API. I was surprised how easy it is in Wordpress. I was looking for simple solution in Wordpress, and i found it in file wp-includes/pluggable.php (where is function wp_mail() defined). Obviously Wordpress developers thinking a lot about usability for other developers, and they simply allow override the function by defining your own function before wp-includes/pluggable.php is included. So you can simply write your own plug-in overriding the function wm_mail().
You can use following code as template for your own wp_mail() override. Don't forget change plug-in name, description, author, author uri, plugin uri. Then use replace yourplugin_ prefix with your own plug-in prefix. Also check the code of both functions, and add original source code from function wp_mail() in your function wp_mail() defined in your plug-in.
/*
Plugin Name: Your plug-in
Description: Your plug-in description
Version: 1.0
Author: yourname
Author URI: http://yourweb.com
Plugin URI: http://pluginweb.com
*/
/**
* Check if this plug-in is enabled
* // YOU PROBABLY WOULD LIKE TO CHANGE THIS TO SOMETHING ELSE
*/
function yourplugin_enabled() {
return 1;
}
/**
* Send email, using phpmailer From, Subject, Body, and $to (phpmailer doesn't have public access to recipients)
* PLEASE NOTE THIS CODE MAY NOT ACTUALLY WORK BECAUSE WASN'T TESTED
*/
function yourplugin_send( $phpmailer, $to ) {
if ( is_array( $to ) ) {
$to = implode( ',', $to );
}
$headers = 'From: ' . $phpmailer->From;
mail($to, $phpmailer->Subject, $phpmailer->Body, $headers);
}
// YOU WILL HAVE CHECK IF wp_mail() IS NOT DEFINED BY WORDPRESS CORE OR SOMEWHERE ELSE
if ( yourplugin_enabled() && !function_exists('wp_mail') ) {
/**
* This was wp_mail() funtion from Wordpress 3.2.1
*
* @param string|array $to Array or comma-separated list of email addresses to send message.
* @param string $subject Email subject
* @param string $message Message contents
* @param string|array $headers Optional. Additional headers.
* @param string|array $attachments Optional. Files to attach.
* @return bool Whether the email contents were sent successfully.
*/
function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
// YOU PROBABLY WILL WANT LEFT WORDPRESS ORIGINAL CODE HERE
// LOOK FOR THE END OF THIS FUNCTION AND REPLACE $phpmailer->Send() with your function
// Send!
try {
//$phpmailer->Send();
return yourplugin_send( $phpmailer, $to );
} catch ( phpmailerException $e ) {
return false;
}
} // end wp_mail
} // end yourplugin_enabled()












