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?
I assumed that your smtp setting are perfect.
/wp-content/themes/wptheme/partials/notify.php
instead of this try making template file and give permalink in$.post()
or put file inwp-content/notify.php
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:
Then do your request to admin-ajax.php (in
js/script.js
then):Then add the following to your functions.php theme file: