wp_mail
Filters the email recipients, subject, message, headers, and attachments before an email is sent.
add_filter( 'wp_mail', $callback, 10, 1 );
Description
Allows developers to modify the arguments of the `wp_mail()` function before an email is sent. This is useful for changing the recipient, subject, message, headers, or attachments. It fires just before the email is processed for sending.
Usage
add_filter( 'wp_mail', 'your_function_name', 10, 1 );
Return Value
The filtered value.
Examples
<?php
/**
* Example of using the wp_mail filter to modify outgoing emails.
*
* This function intercepts emails sent by WordPress and appends a custom
* footer to the message body. It's useful for branding, adding disclaimers,
* or including tracking information.
*/
add_filter( 'wp_mail', 'my_custom_wp_mail_filter', 10, 1 );
/**
* Modifies the email message to append a custom footer.
*
* @param array $args An array of arguments for sending an email.
* Includes 'to', 'subject', 'message', 'headers', 'attachments'.
* @return array The modified arguments array.
*/
function my_custom_wp_mail_filter( $args ) {
// Ensure we have a message to modify.
if ( ! empty( $args['message'] ) ) {
$custom_footer = "nn---nSent by My Awesome Plugin.";
$args['message'] .= $custom_footer;
}
// It's crucial to return the modified arguments array.
return $args;
}
?>
Placement
This code should be placed in the functions.php file of your active theme, a custom plugin, or using a code snippets plugin.
Source Code
src/includes/class.DisableEmailsPHPMailerMock.php:123
// set default From name and address
$this->phpmailer->FromName = 'WordPress';
$this->phpmailer->From = 'wordpress@' . $sitename;
// let hookers change the function arguments if settings allow
if ( $plugin->options['wp_mail'] ) {
extract( apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) ), EXTR_IF_EXISTS );
}
// set mail's subject and body
$this->phpmailer->Subject = $subject;
$this->phpmailer->Body = $message;
// headers