Skip to content

Instantly share code, notes, and snippets.

@robertpainsi
Last active October 17, 2019 10:35
Show Gist options
  • Save robertpainsi/c24ad305c1491ef9b057ee53bac0fe9c to your computer and use it in GitHub Desktop.
Save robertpainsi/c24ad305c1491ef9b057ee53bac0fe9c to your computer and use it in GitHub Desktop.
WordPress - Use from email if specified in header, else fall back to default
<?php
function my_from_name( $name ) {
if ( $name === 'WordPress' ) {
return 'Default Sender';
} else {
return $name;
}
}
add_filter( 'wp_mail_from_name', 'my_from_name', 10, 1 );
function my_from_email( $email ) {
if ( strpos( $email, 'wordpress@' ) === 0 ) { // WordPress's default email is 'wordpress@' . $sitename
return 'default@email.com';
} else {
return $email;
}
}
add_filter( 'wp_mail_from', 'my_from_email', 10, 1 );
// Sending email using default from name and email (e.g. 'Default Sender' and 'default@email.com')
wp_mail( 'to@example.org', 'Subject', 'Message' );
// Sending email using custom from name and email (e.g. 'Custom Email' and 'custom@email.com')
wp_mail( 'to@example.org', 'Subject', 'Message', array( 'From: Custom Email <custom@email.com>' ) );
@robertpainsi
Copy link
Author

robertpainsi commented Oct 17, 2019

If you don't want to specify a from name and email in the headers every time using wp_mail, you can add the filters wp_mail_from and wp_mail_from_name. This will set the default from name and email.

However, sometimes you still want to use wp_mail with a custom from name and email. Just setting the from header field won't work because WordPress will always use the default one set by the filters wp_mail_from and wp_mail_from_name.

Many resources tell you to remove both filters just before sending the mail and readd them afterwards. IMO this isn't a great solution. This gist shows an alternative way to do it.

To use the from name and email set in the headers or if not set, default name and email, just use the code above. IMO both ways to locally send an email with a different from name and email as the default values aren't ideal.

  • Hard-coded strings 'WordPress' and 'wordpress@': may change in the future. Upgrading WordPress may break the default from name and email functionality (will be 'WordPress <wordpress@' . $sitename . '>').

  • If you use remove_filter (as many resources do, not shown here), you have to remember to remove the filters before sending a mail with wp_mail and readd them afterwards.

If you know a better solution or I missed something, please let me know.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment