首页 > 解决方案 > WordPress:template_redirect 钩子发送 wp_mail 两次

问题描述

我有几个受限页面。如果用户尝试访问这些内容,我会通过电子邮件警告他们,并使用wp_mail用户名、URL、时间等数据提醒管理员。为此,我正在使用template_redirect钩子。

一切正常,但wp_mail发送电子邮件两次。我不确定我的代码有什么问题以及为什么它会发送两次。

回调函数和钩子

cp_write_log()是一个自定义日志函数,可以将日志写入debug.log. 条目还会向 debug.log 文件添加两次。

function module_permission_check() {

    if ( is_page() ) {

        $template  = get_page_template_slug();
        $post_type = get_cpt_for_template( $template );

        if ( ! is_current_user_granted_for_module( $post_type ) ) {
            $user = wp_get_current_user();

            //$headers = [ 'From: ' . get_bloginfo( 'name' ) . ' <' . get_bloginfo( 'admin_email' ) . '>' ];

            // user message
            $message = str_replace(
                [ '%%name%%', '%%sitename%%' ],
                [
                    $user->data->user_login,
                    get_bloginfo( 'name' ),
                ],
                cp_get_setting( 'warning_unauthorized_email_message' )
            );

            if ( wp_mail( $user->data->user_email, 'Warning: Unauthorized access', $message ) ) {
                cp_write_log( 'Email sent to ' . $user->data->user_email );
            }

            global $wp;
            $current_url   = home_url( add_query_arg( [], $wp->request ) );
            $admin_message = "Hello,\n\nA member has tried to access unauthorized content.\n\nUsername: {$user->data->user_login}\nURL: {$current_url}\nLocal Time: " . current_time( 'l, j F Y \a\t H:i ' ) . "\nUTC Time: " . current_time( 'l, j F Y \a\t H:i ', TRUE ) . "\n\nRegards,\n" . get_bloginfo( 'name' );

            if ( wp_mail( get_bloginfo( 'admin_email' ), 'Alert: Unauthorized access', $admin_message ) ) {
                cp_write_log( 'Email sent to admin' );
            }

            wp_redirect(home_url());
            exit();
        }
    }

}

add_action('template_redirect', 'module_permission_check');

更新

我发现它只发生在 Safari 浏览器上。很奇怪。

标签: wordpresswp-mailtemplate-redirect

解决方案


推荐阅读