onClick of span tag send notification email in Wor

2019-06-10 08:58发布

I have a span tag that is part of a form (but not the final submit form), it advances the user from the first question to the second. Onclick of this button I want to send a simple email notification to a hard-coded email saying that a new entry has been added. I am using WordPress.

My HTML is as follows (can't be changed)

<span class="button next email-enter">
    <span class="txt">Get Started</span>
</span>

I'm using the following jquery function with ajax (console.log is successful):

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

and then I've created a notify.php file that contains the following:

<?php wp_mail( 'myemail@myemail.com', 'The subject', 'The message' ); ?>

Although the click function works, the ajax/wp-mail is not working (I'm not getting an email). How can I edit this code to send an email notification onclick of this span?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-10 09:24

I assumed that your smtp setting are perfect.

  $('.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 instead of this try making template file and give permalink in $.post() or put file in wp-content/notify.php

查看更多
【Aperson】
3楼-- · 2019-06-10 09:28

It couldn't work because you're trying to use a Wordpress function without being in a Wordpress environment. Even if you placed your script in your theme folder, as you call it directly it doesn't get through the Wordpress Core. If you look into your error log you should see an error saying that wp_mail is undefined.

An easy solution would be to just use the PHP mail function instead. Though I suggest to do this in a proper way, with the Wordpress AJAX functionality.

First, add the following to your theme functions.php in order to define a new JS var with the path to admin-ajax.php, and set as first parameter the handler name of your script - assuming here script.js is where your will do your ajax request:

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');

Then do your request to admin-ajax.php (in js/script.js then):

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

Then add the following to your functions.php theme file:

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');
查看更多
登录 后发表回答