How to run custom PHP code in WordPress – the right way
I’ve recently been asked to look at integrating some complex forms into a WordPress powered site. None of the current plugins satisfied our (multi-lingual) needs, so the next simplest approach appeared to be integrating PHP code with WordPress. (I had considered integrating Kohana, my favoured PHP framework, as there is a module that allows easy integration, but this seemed overkill for a few forms).
Running PHP code from within WordPress is nothing new. There are numerous plugins. I opted for Exec-PHP, partly because it gets high user ratings and the developer has provided feedback on his site, and partly because it worked for me first time.
Having installed the plugin, it was simple to create a Page, add some PHP code using the traditional PHP tags . However, once I started writing code in anger, I began to understand that to run the code efficiently, and to give the end-user a good experience, simply placing code in the page (blog entry) is too simplistic.
The key issues, is that the PHP code is evaluated at run-time, using the PHP eval() function. This function is highly inefficient. So, the first improvement was to move the bulk of the code to a separate PHP file and include it. This way, the only code evaluated is the include statement.
I chose to put my included code in a folder called custom-php within the WordPress wp-content folder. The best way to reference the file is using the ABSPATH constant provided by WordPress, as follows:
<? require_once(ABSPATH. '/wp-content/custom-php/contact-form.php'); ?>
Now I can simply place my PHP code in the external file for inclusion. So far, so good. But it wasn’t long until I hit my next hurdle. I need to send an email when the form is submitted. Nothing too taxing there. In fact, this is super simple thanks to the @wp_mail WordPress tag.
Now, normally when writing a PHP form script, the form is POSTed to the server, the server sends the email using some SMTP library, and then the script renders an HTML page ( or View if using an MVC framework). And if you’re a good developer, you’ll actually perform an HTTP redirect instead, to prevent double form submission (see this article on Wikipedia).
However when PHP code is executed within a WordPress page, some of the response has already been sent. This has two side effects:
- Firstly, the page renders in the browser until it reaches the script; waits until the email has been sent, and then continues rendering the rest of the page/
- Secondly, as part of the response has already been sent, it is not possible to modify the HTTP headers, and hence a redirect cannot be sent.
So, we need a way to run the script before the response is sent. Here’s my solution:
Firstly, the PHP page included in the WordPress page, contains an HTML form. I add to the form a hidden field so that it can easily identified when POSTed e.g.:
<form method="POST" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> <input type="hidden" name="form-name" value="contact" /> <div style="text-align:left; border: 1px solid #bbb; padding:10px;"> <div> <label for="name">name</label> <input type="text" name="name" id="name" /> </div> <div> <label for="email">email</label> <input type="text" name="email" id="email" /> </div> <div> <label for="message">message</label> <textarea name="message" id="message" style="width:250px; height:100px"></textarea> </div> <input type="submit" value="go" /> </div> </form>
Now, when the form is submitted, I am able to detect it, and therefore process the form submission prior to rendering the page. I do this by adding some code to the WordPress page template. I opted to add some more include code to the first line of the header.php file within my theme, like so:
<?php require_once(ABSPATH. '/wp-content/custom-php/contact-form-test.php'); ?>
There may be a better place to put this code (wp-config, wp-settings ?). I’m no WordPress guru, and I’m happy to be educated.
The contact-form-test.php code is as follows:
<?
session_start();
if($_POST['form-name'] AND "contact" === $_POST['form-name']) {
require_once(ABSPATH. '/wp-content/custom-php/contact-form-functions.php');
send_message();
}
?>
This is fairly simple code. We test to see if our form was posted, and if so include the code to send the email. No point including it unless we need to. The key is, the code is now included before any other WordPress code executes.
For completeness, the contact-form-functions.php is as follows:
<?
function send_message()
{
$subject = "Test email form WordPress";
$body = $_POST['message'];
$recipient = "rocky-racoon@abbeyroad.co.uk";
$success = @wp_mail($recipient, $subject, $body);
if($success) {
session_start();
$_SESSION["mail_message"] = "Thank you. your message has been sent.";
header( 'Location: '.$_SERVER['HTTP_REFERER'] ) ;
}
else {
$GLOBALS["mail_message"] = "Euston, we have a problem.";
}
}
?>
We use WordPress’ mail functionality to send the email. If it sends OK, we perform an HTTP redirect. First we also set a flashvar using the PHP $_SESSION as, due to the redirect, we cannot use a $GLOBAL as it obviously goes out of scope.
One final change is required to contact-form.php to retrieve the success (or error) message. The following code is placed before the HTML form:
<?php
if(isset($GLOBALS["mail_message"])) {
echo "<p>".$GLOBALS["mail_message"]."</p>";
}
if(isset($_SESSION["mail_message"])) {
echo "<p>".$_SESSION["mail_message"]."</p>";
unset($_SESSION["mail_message"]);
}
?>
This solution is useful for an custom PHP code that is server-intensive, be it database queries, web service calls or sending email.
Hope you found this useful

Excellent tip to Include the php code rather than just drop it in the page/post!
Thanks for sharing
I’ve got a problem, I got this page done topxxname.php and uploaded it to wpcontent/themes/mytheme/ and when i try to open on browser that file my wp send me to the 404 page!
How i can add custom php pages to the themes folder and run them?
If i do ur tutorial it will work ?
Thanks
@carlitos – you can’t just upload a file and access it using WP. Everything goes through the controller, index.php. You need to create a PAge within WP, and run your code within this.
yeah thank you i finally figure it out
Thanks for taking the time to post this. It has saved me hours and at my age…that is important :)
Thanks for this article. Makes sense but I cannot get it to work.
When I first display the form page it begins with this error:
Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/myacctname/public_html/mywpsitename/wp-content/themes/formtheme/header.php:8) in /home/myacctname/public_html/mywpsitename/wp-content/custom-php/contact-form.php on line 2
In my themes header.php the first line reads:
…and in “contact-form-test.php” the entire module is
…and in “contact-form-functions.php” the entire module is
The error message appears, followed by the contact form itself. If I fill out the contact form and click GO then I get the “Thank you. your message has been sent” message, but I never get the email.
As a test I tried commenting out the session-start command at the beginning of “contact-form.php”. and that did eliminate the error message, but now when I fill out the form and click GO I no longer get the ‘thank you’ message.
I researched the error message and read that it might be caused by stray nonblank characters either before the but it looks like my Notepad++ is set to Unix/ANSI so I don’t think that is the problem.
Any suggestions on 1) why the error message, and 2) why I got the “…your message has been sent” and yet received no email?
TIA
Hi Joe. You’re on the right track with the stray characters. To start a session the headers need modifying in the HTTP response. This cannot happen once the response has started being written. This is a classic gotcha with PHP when you are mixing server-side code with client-side HTML. If you have so much as a space or carriage return outside of the PHP tags, prior to the session_start call, then you are actually sending a response. You have to work through ALL the files that might be loaded before the session_start call. This includes those loaded by WordPress such as index.php, wp-config.php. If there’s a new line after the closing PHP tag, this cvould ber the culprit. Often, you’ll find there is no closing tag, to avoid this error. Quite likely it’s header.php, contact-form-test.php, contact-form-functions.php or contact-form.php.
If sessions aren’t working, then you will not see the message. It needs to be set in session so it can subsequently be pulled out after the redirect.
As to why you’re not receiving email, the code I posted is using Worpress’ underlying mail function. This means that whatever WP uses, the function uses. Can you send mail outside of this script? If not, you might need to configure WP with an SMTP plugin, rather than using the native sendmail() function.
god luck
Thanks for the encouragement, but I looked at the header.php and the other files you mentioned but no luck: I’m still getting the “headers already sent” message whenever I display the contact form page (all other site pages are fine).
I also tried relocating the “require_once(ABSPATH. ‘/wp-content/custom-php/contact-form-test.php” to the wp-configure.php, and also deactivating all plugins but still I get the same “headers already sent” error message.
If you have any other ideas – or perhaps know of some diagnostic tool to perhaps capture the outgoing stream and that would reveal the culprit (i.e., the code that is possibly sending the stray character(s) after the php closing bracket) then I’m all ears.
I think the problem Joe is having is the same one I am having. When you try to use session_start() in contact-form.php where contact_form.php isn’t the only thing included on the page, PHP complains that headers are already sent.
My form sends just fine, but I can’t extract the error message to display it. Here’s my set up:
contact-form-test.php is the first line in header.php
contact-form-functions.php does its job and sends the mail through WordPress
contact-form.php is included from index.php since I want the form to appear on my home page, toward the bottom. So when contact-form.php loads, the session_start() in line 2 of contact-form.php that should resume the session to pull out the error message makes PHP complain that headers have already been sent out (since it’s almost done rendering the entire page). I can’t see how any of this would actually work.
Maybe you can shed some light on how you got this going? Perhaps showing the code for the page that calls contact-form.php would be helpful.
TO ANYONE HAVING PROBLEMS WITH THIS
I finally fixed this after nearly a day of debugging. Here’s the strategy:
in the header.php of my template, I have:
if (!session_id()) {
session_start();
}
require_once(ABSPATH. ‘…/contact-form-test.php’);
contact-form-test.php:
if($_POST['form-name'] AND “contact” === $_POST['form-name']) {
session_register(‘mail_message’);
require_once(ABSPATH. ‘…/contact-form-functions.php’);
send_message();
}
contact-form-functions.php
function send_message()
{
$subject = ‘Test email form WordPress’;
$body = $_POST['message'];
$recipient = ‘shaun@tarves.net’;
$success = @wp_mail($recipient, $subject, $body);
if($success) {
$_SESSION['mail_message'] = ‘Thank you. your message has been sent.’;
session_write_close();
header( ‘Location: ‘.$_SERVER['HTTP_REFERER'].’#contact’);
}
else {
$GLOBALS['mail_message'] = ‘Euston, we have a problem.’;
}
}
Doing it this way allows you to only have to include session_start() one time, and the key here is session_write_close(). For some reason, upon page redirection, PHP often loses session data. Ensuring the write is closed makes everything work.
Thanks so much for this great tutorial!
Shaun, Joe
I just took a look at my code, and I had modified it since the orignal post. I moved the session_start() call to the contact-form-test.php include. Looking at your fix, this might be the reason. (I’ve modified this post to show the update).
and yes, PHP will lose all session data unless you tell it otherwise. Check out the wp_unregister_GLOBALS() function in wp-settings.php
hi,
the only way I got this to work was to put the session_start() in the index.php of my theme ? http://bugs.php.net/bug.php?id=14636
Hi
Thanks for this.
I also found a plugin which inserts a shortcode for php includes.
http://www.amberpanther.com/contributions/wp-include-file/
It would be good to hear your thoughts on this. Goo didea or not?
thanks
Neil
Plugin looks good. Only thing to watch is *when* it executes your code. If it calls the include part way through the page, you could have session issues
Thanks for the tips! I will try this script in my WP blog
Let me try ;) I am switching from blogspot to wordpress
I’m also giving it a try. Great article by the way.