I’m using wp_mail filter function.
add_filter('wp_mail','check_the_mail_content');
If my condition satisfied then the mail should go, otherwise I need to stop, my function is
add_filter('wp_mail','check_the_mail_content');
function check_the_mail_content($query){
if(mycondition){
//mail should go.
}
else{
//stop the mail.
}
}
Filter
'phpmailer_init'
, not'wp_mail'
. To prevent sending the mail out reset the PHPMailer object.Prototype (not tested):
//dont work for me:
$phpmailer = new stdClass;
//for stop wp_mail function use:
function my_action( $phpmailer )
{
if( condition )
{
$phpmailer->ClearAllRecipients();
}
}
add_action( 'phpmailer_init', 'my_action' );
Unfortunately, that particular filter isn’t verified after it’s used. Here is the use of that filter in core:
So all that filter does is populate the
$to
,$subject
,$message
,$headers
, and$attechments
varaibles. It’s not an action hook, so while you probably could throw some kind of termination operation in there, you really shouldn’t. Ideally, you’d be able to returnfalse
from your filtering function to kill operation, but the function isn’t set up that way.Instead, I recommend hooking to the
phpmailer_init
action. It’s the last action in thewp_mail()
function and it passes a reference to the actual$phpmailer
object that does the mailing.This untested function should prevent mail from sending:
This should replace the
$phpmailer
object with an instance of your fake mailer class. This fake class only contains aSend()
method that immediately throws an exception of typephpmailerException
. Thewp_mail()
function will catch this exception and returnfalse
by default.Not the most performant solution in the world … you should really be checking conditions before even calling
wp_mail()
(as suggested by @Zaidar), but if you must use a hook, this is one way to do it.Rather than hooking on
phpmailer_init
, why not just set$query['to'] = '';
andreturn $query;
inside thewp_mail
hook?You can do this using the
wp_mail
filter by returning an empty message. WordPress will not send the email.