onClick标记在WordPress中发送通知电子邮件

我有一个span标签,它是表单的一部分(但不是最终的提交表单),它将用户从第一个问题推进到第二个问题。 点击此按钮,我想向硬编码的电子邮件发送简单的电子邮件通知,说明已添加新条目。 我正在使用WordPress。

我的HTML如下(无法更改)

 

我在ajax中使用以下jquery函数(console.log成功):

 $('.email-enter').on('click', function(){ console.log('button is clicked'); $.post("/wp-content/themes/wptheme/partials/notify.php"); }); 

然后我创建了一个包含以下内容的notify.php文件:

  

虽然点击function有效,但是ajax / wp-mail无法正常工作(我没有收到电子邮件)。 如何编辑此代码以发送此跨度的电子邮件通知?

它无法工作,因为您尝试使用Wordpressfunction而不是在Wordpress环境中。 即使您将脚本放在主题文件夹中,直接调用它也无法通过Wordpress Core。 如果查看错误日志,您应该会看到一条错误消息,指出wp_mail未定义。

一个简单的解决方案就是使用PHP mailfunction。 虽然我建议以适当的方式使用Wordpress AJAXfunction 。

首先,将以下内容添加到主题functions.php中,以便使用admin-ajax.php的路径定义新的JS var,并将脚本的处理程序名称设置为第一个参数 – 假设此处script.js是您的意愿做你的ajax请求:

 function my_load_scripts() { wp_enqueue_script('my_script', get_stylesheet_directory_uri() . '/js/script.js', array('jquery'), false, true ); wp_localize_script('my_script', 'MyAjax', array('ajaxurl' => admin_url('admin-ajax.php'))); } add_action('wp_enqueue_scripts', 'my_load_scripts'); 

然后请求admin-ajax.php (在js/script.js ):

 $('.email-enter').on('click', function() { $.post(ajaxurl, {action: 'send_mail'}); }); 

然后将以下内容添加到functions.php主题文件中:

 function ajax_send_mail() { wp_mail('myemail@myemail.com', 'The subject', 'The message'); } add_action('wp_ajax_send_mail', 'ajax_send_mail'); add_action('wp_ajax_nopriv_send_mail', 'ajax_send_mail'); 

我认为你的smtp设置是完美的。

  $('.email-enter').on('click', function(){ console.log('button is clicked'); $.post("/wp-content/themes/wptheme/partials/notify.php"); }); 

/wp-content/themes/wptheme/partials/notify.php而不是这个尝试制作模板文件并在$.post()提供永久链接或将文件放在wp-content/notify.php