Filter uncanny-learndash-toolkit

wp_mail_charset

Filters the character set used for outgoing emails, allowing modification before the email is sent.

add_filter( 'wp_mail_charset', $callback, 10, 1 );

Description

Filters the character set used for emails sent by WordPress. This hook allows developers to dynamically change the character set, influencing how email content is encoded and displayed by email clients. It's typically used to ensure proper display of international characters or to adhere to specific email standards.


Usage

add_filter( 'wp_mail_charset', 'your_function_name', 10, 1 );

Parameters

$this (mixed)
This parameter is the PHPMailer instance that is being modified.

Return Value

The filtered value.


Examples

/**
 * Filter the email charset to ensure UTF-8 compatibility.
 *
 * This function checks if the email content type is set to 'text/html'
 * and if so, it forces the CharSet to 'UTF-8' to prevent character
 * encoding issues with HTML emails.
 */
add_filter( 'wp_mail_charset', 'my_wp_mail_charset_utf8', 10, 1 );

function my_wp_mail_charset_utf8( $charset ) {
	// Access global WordPress object or a plugin's option if needed.
	// For demonstration, we'll assume we want to force UTF-8 for all emails.
	// In a real scenario, you might check wp_mail_content_type or a custom option.

	// Let's imagine we're checking a global variable set elsewhere,
	// or directly the 'wp_mail_content_type' option if it's not already set.
	$content_type = !empty( $GLOBALS['wp_mail_content_type'] ) ? $GLOBALS['wp_mail_content_type'] : get_option( 'wp_mail_content_type', 'text/plain' );

	if ( 'text/html' === $content_type && 'UTF-8' !== $charset ) {
		return 'UTF-8';
	}

	return $charset;
}

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:196

if ( $plugin->options['wp_mail_from_name'] ) {
			$this->phpmailer->FromName = apply_filters( 'wp_mail_from_name', $this->phpmailer->FromName );
		}
		if ( $plugin->options['wp_mail_content_type'] ) {
			$this->phpmailer->ContentType = apply_filters( 'wp_mail_content_type', $this->phpmailer->ContentType );
		}
		if ( $plugin->options['wp_mail_charset'] ) {
			$this->phpmailer->CharSet = apply_filters( 'wp_mail_charset', $this->phpmailer->CharSet );
		}
		if ( $plugin->options['phpmailer_init'] ) {
			do_action( 'phpmailer_init', $this->phpmailer );
		}

		return true;
	}


Scroll to Top