钩子文档

wp_mail_failed

💡 云策文档标注

概述

wp_mail_failed 是一个 WordPress 钩子,在捕获到 PHPMailerPHPMailerException 后触发,用于处理邮件发送失败的情况。它传递一个包含错误信息和邮件数据的 WP_Error 对象,便于开发者进行调试或错误处理。

关键要点

  • 触发时机:在 wp_mail() 函数发送邮件时,如果捕获到 PHPMailerPHPMailerException 异常,则会触发此钩子。
  • 参数:传递一个 WP_Error 对象,其中包含 PHPMailerPHPMailerException 的错误消息,以及一个数组,数组内包含邮件收件人、主题、消息、头部和附件等数据。
  • 用途:主要用于调试 wp_mail() 函数,例如通过添加动作来显示详细的错误信息,但建议仅在调试环境中使用。
  • 版本历史:自 WordPress 4.4.0 版本引入。

代码示例

// 显示 wp_mail() 错误
add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
function onMailError( $wp_error ) {
    echo "";
    print_r($wp_error);
    echo "";
}

注意事项

  • 此钩子主要用于调试目的,在生产环境中应谨慎使用,以避免暴露敏感信息。
  • 示例代码展示了如何添加一个动作来打印 WP_Error 对象,帮助开发者获取更详细的错误信息。

📄 原文内容

Fires after a PHPMailerPHPMailerException is caught.

Parameters

$errorWP_Error
A WP_Error object with the PHPMailerPHPMailerException message, and an array containing the mail recipient, subject, message, headers, and attachments.

Source

do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_data ) );

Changelog

Version Description
4.4.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Debugging wp_mail() can be a lot easier with this simple method.
    It will display a more helpful error message (the original phpmailer error) than WordPress will by default.
    Just add this function to display the real wp_mail() error.
    But only use this for debugging.

    // show wp_mail() errors
    add_action( 'wp_mail_failed', 'onMailError', 10, 1 );
    function onMailError( $wp_error ) {
    	echo "<pre>";
        print_r($wp_error);
        echo "</pre>";
    }