Need clarification on how to correctly call wp_mail()

I want to call wp_mail() from a non-template PHP file, but when I do, it fails and I don’t understand why. For example, let’s say I have a PHP file that consists of only this:

<?php
    echo 'hi';
    $mail_sent = wp_mail('example@example.com', 'subject', 'message');
    echo $mail_sent;
?>

If I load that PHP file directly in my browser, only “hi” will print. If I remove echo 'hi'; altogether, nothing is printed, which indicates to me that wp_mail() cannot be called in this particular context. However, if I add /* Template Name: SomeName */ to the file and create a new page using SomeName as its template, wp_mail() executes correctly. Clearly, I’m missing some key bit of information regarding how to correctly call wp_mail().

Read More

The reason I want to do this is because the theme I’m using came with a contact form that submits email via an ajax request roughly like this:

form.submit(function() {
    $j.ajax({
        type: 'GET',
        url: "http://www.example.com/wp-content/themes/themeX/send_mail.php",
        data: form.serialize(),
    });
});

Currently, send_mail.php calls the PHP mail() function which “works” but is extremely flaky. I want it to call wp_mail() so I can take advantage of this plugin which sends mail using a SMTP server. So my question is: how can I get wp_mail() to work in this situation?

Thanks!

Related posts

Leave a Reply

3 comments

  1. The standalone script will not load WordPress, so it doesn’t have a wp_mail() function. WordPress has its own built-in Ajax handlers which you can leverage and have access to all WordPress functionality within those Ajax calls.

  2. Alternatively, include the WordPress functions in your standalone script as follows

    require_once('wp-blog-header.php'); 
    

    I find the WP ajax functions are not always the best way to do things, so writing your own AJAX handler is quite valid.