wordpress wp_mail() function with jquery $.post()

I’m building custom contact form on wordpress using jquery $.post() function.

$.post(tmpl_dir + '/bugreport.php',{ name:name, email:email, message:message }, function(data) {
                if ( data ) alert( 'thanks for answer' )
                else alert('error sending, please try again.');

            })

(tmlp_dir is theme directory path)

Read More

here is bugreport.php file:

<?php 
if ( isset($_POST['name']) && isset($_POST['email']) &&isset($_POST['message']) ) {
    $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message'];
    $send_to = "mail@mail.com";
    $subject = "Question from " . $name;
    $success = wp_mail($send_to,$subject,$message);
            if ($succsess) return true
            else return false;
}
?>

I’m getting an error from wordpress that says: wp_mail() function not defined.
How can i let my php file use wp_mail() function?

Thanks.

Related posts

Leave a Reply

1 comment

  1. You should use the wordpress ajax hook in order to get wordpress classes.

    http://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)

    I would recommend cleaning the code a bit and adding a Nonce check, but your code should look something like this:

    js:

    jQuery.post(
        MyAjax.ajaxurl, 
        {
            'action': 'send_message',
            'name':'name', 
            'email':'email', 
            'message':'message'
        }, 
        function(response){
            alert('The server responded: ' + response);
        }
    );
    

    php:

    add_action( 'wp_ajax_send_message', 'do_send_message' );
    
    function do_send_message() {
    
      if ( isset($_POST['name']) && isset($_POST['email']) &&isset($_POST['message']) ) {
        $name = $_POST['name']; $email = $_POST['email']; $message = $_POST['message'];
        $send_to = "mail@mail.com";
        $subject = "Question from " . $name;
        $success = wp_mail($send_to,$subject,$message);
                if ($succsess) return true
                else return false;
      }
    
    }
    

    To load your js file and vars add this to functions.php or your plugin.

    $myvars = array( 
        'ajaxurl' => admin_url( 'admin-ajax.php' ),
    );
    wp_enqueue_script( 'my-ajax-request', plugins_url( '/path/to/somefile.js', __FILE__ ) );
    wp_localize_script( 'my-ajax-request', 'MyAjax', $myvars );