Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to call wp_mail() from a non-template php file, but when I do so 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().

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!

share|improve this question

3 Answers 3

up vote 2 down vote accepted

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.

share|improve this answer
1  
Thanks for the tip. Just in case any other wordpress noobs encounter a similar issue, I found this article very helpful: wp.smashingmagazine.com/2011/10/18/how-to-use-ajax-in-wordpress –  Nick Mar 12 '12 at 3:30

wp_mail is a Pluggable Function so you should be able to call wp-includes/pluggable.php and then have the ablilty to use wp_mail().

share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.