Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Andrew Folts
Andrew Folts
14,238 Points

All WP functions UNDEFINED in mailer.php when creating a contact form?

I'm creating a simple AJAX contact form with the ACTION being "/php/mailer.php".

However, when I submit the form, I get an UNDEFINED error in the console for any Wordpress functions I use in that file. For example "wp_mail() or "get_site_url()".

What the heck is going on???

1 Answer

Luke Towers
Luke Towers
18,572 Points

None of the WordPress code has been loaded by your mailer.php file. The way PHP works is it is executed on a per file basis. So, when someone makes a normal request to your WordPress website, it is all being run through index.php which takes care of the loading of all of the WordPress PHP files required.

In order to have access to those same WP functions, your mailer.php script must load the WordPress files itself before it can use the functions contained within. There is a great StackOverflow answer addressing just this use case, the gist of it however is that you need to include the wp-load.php file in your mailer.php file through the addition of

require_once(PATH/TO/wp-load.php); 

to the top of your mailer.php file.

Andrew Folts
Andrew Folts
14,238 Points

Ah, I see. Thanks for a great explanation!

Luke Towers
Luke Towers
18,572 Points

No problem, happy to help out!