我创建的wp\\U邮件功能有问题,当我按下按钮时,它会发送电子邮件。当您注销时,它确实工作得很好。但一旦我登录,它就会停止工作。这不是一个能力问题,因为我作为超级管理员也会遇到这个错误。
为什么会发生这种情况?我正在使用PHP函数和Ajax一起发送电子邮件,Javascript函数称为onclick。
function searchEmail(email,title,content,location) {
var admin_url = admin_ajax.ajaxurl;
$.ajax({
type: "POST",
url: admin_url,
datatype: "html",
data: { \'action\': \'search_notify_email\', email: email, title: title, content: content, location: location },
success: function() {
searchNotification();
},error:function() {
searchNotificationError();
}
});
}
PHP:
function search_notify_email() {
// Set variables
$email = $_POST[\'email\'];
$title = $_POST[\'title\'];
$content = $_POST[\'content\'];
$location = $_POST[\'location\'];
// Change Email to HTML
add_filter( \'wp_mail_content_type\', \'set_email_content_type\' );
$to = $email;
$subject = "Test subject!";
$message = "<img src=\'favicon.png\'><br><b>Test!</b>";
if (empty($title)) {
$message .= "<br><br><b>" . $_POST[\'content\'] . "</b> test.<br> ";
}
else {
$message .= "<br><br><b>" . $_POST[\'content\'] . "</b> test " . $_POST[\'title\'] . " test.<br> ";
}
if (!empty($location)) {
$message .= "Test <b>" . $_POST[\'location\'] . "</b>";
}
$headers[] = \'From: Testing <noreply@example.com>\';
if ( wp_mail($to, $subject, $message, $headers) ) {
// Success
} else {
// Error
}
die();
// Remove filter HTML content type
remove_filter( \'wp_mail_content_type\', \'set_email_content_type\' );
}
add_action(\'wp_ajax_nopriv_search_notify_email\', \'search_notify_email\');
add_action(\'wp_ajax_search_notify_emaill\', \'search_notify_email\');
// Reset Email content type to standard text/html
function set_email_content_type() {
return \'text/html\';
}
最合适的回答,由SO网友:Jacob Peattie 整理而成
针对登录用户运行的钩子中有一个拼写错误:
add_action(\'wp_ajax_search_notify_emaill\', \'search_notify_email\');
还有一个额外的
l 在挂钩名称中。钩子名称必须相同,除了
nopriv_, 因此,您应该:
add_action(\'wp_ajax_nopriv_search_notify_email\', \'search_notify_email\');
add_action(\'wp_ajax_search_notify_email\', \'search_notify_email\');
当您使用
action WordPress运行挂钩
wp_ajax_{$action} (其中
$action 参数是否随请求一起传递)如果您已登录,或
wp_ajax_nopriv_{$action} 如果用户未登录。由于您在登录版本中使用了不正确的挂钩名称(由于输入错误),您的
search_notify_email() 用户登录时,函数未挂接运行。