Skip to content

Instantly share code, notes, and snippets.

@MaximeCulea
Created April 30, 2020 11:16
Show Gist options
  • Save MaximeCulea/12cadf78721eaf6be3b0dbfb3d109617 to your computer and use it in GitHub Desktop.
Save MaximeCulea/12cadf78721eaf6be3b0dbfb3d109617 to your computer and use it in GitHub Desktop.
Hooks in order to customize WordPress WP Mail headers.
<?php class MC_Customize_WP_Mail {
private $sender_mail;
private $sender_name;
private $reply_mail;
private $replay_name;
/**
* Set custom sender mail and name for all sent emails
* and add a reply to mail and name to allow people replying to your sent emails
*
* MC_Customize_WP_Mail constructor.
*
* @param $sender_mail
* @param $sender_name
* @param $reply_mail
* @param $replay_name
*
* @author Maxime Culea
*/
public function __construct( $sender_mail, $sender_name, $reply_mail, $replay_name ) {
$this->sender_mail = $sender_mail;
$this->sender_name = $sender_name;
$this->reply_mail = $reply_mail;
$this->replay_name = $replay_name;
}
public function _init() {
// set higher priority for overwritting settings from others plugins
add_filter( 'wp_mail_from', [ $this, 'set_sender_mail' ], 999 );
add_filter( 'wp_mail_from_name', [ $this, 'set_sender_name' ], 999 );
add_filter( 'wp_mail', [ $this, 'set_reply_to' ] );
}
/**
* Change sender mail with the provided one
*
* @param string $original_sender_mail
*
* @author Maxime Culea
*
* @return string
*/
function set_sender_mail( $original_sender_mail ) {
return $this->sender_mail ?: $original_sender_mail;
}
/**
* Change sender name with the provided one
*
* @param string $original_sender_name
*
* @author Maxime Culea
*
* @return string
*/
function set_sender_name( $original_sender_name ) {
return $this->sender_name ?: $original_sender_name;
}
/**
* Change the Reply To headers with the provide one, if it doesn't exist
*
* @param array $args
*
* @author Maxime Culea
*
* @return array
*/
function set_reply_to( $args ) {
if ( empty( $this->replay_name ) || empty( $this->reply_mail ) ) {
return $args;
}
if ( ! isset( $args['headers'] ) ) {
$args['headers'] = [];
}
// Does it exist already?
if ( stripos( serialize( $args['headers'] ), 'Reply-To:' ) !== false ) {
return $args;
}
$reply_to_line = sprintf( "Reply-To: %s <%s>", $this->replay_name, $this->reply_mail );
if ( is_array( $args['headers'] ) ) {
$args['headers'][] = 'h:' . $reply_to_line;
$args['headers'][] = $reply_to_line . "\r\n";
} else {
$args['headers'] .= 'h:' . $reply_to_line . "\r\n";
$args['headers'] .= $reply_to_line . "\r\n";
}
return $args;
}
}
// Here emails will be sent from MC Website <[email protected]> and people will reply to Maxime Culea <[email protected]>
$mccwpm = new MC_Customize_WP_Mail( '[email protected]', 'MC Website', '[email protected]', 'Maxime Culea' );
$mccwpm->_init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment