Sometimes we might want to integrate subscription, contact, upload forms etc on WordPress front-end. These forms can make a POST request to the wordpress server. In this post I will show you how to handle POST requests in wordpress.
WordPress Requests
During a wordpress request WordPress takes the request URL and using regular expressions it find what to execute and display. Therefore we can make the change GET request as POST request and handle the POST data at a certain point of time needed and this will not harm the normal flow of wordpress.
POST Request to particular page
Suppose you want to display a email subscription form in a particular page then you can use this method:
Put this code inside the page:
{
//do something
echo "Successfully Subscribed"
}
else
{
?>
<form method="post" action="">
<input type="email" name="email">
</form>
<?php
}
Here the page is going to POST back it itself. This method is for a particular URL post. Let’s see how implement POST forms via a plugin i.e., on any page or URL
POST Form via Plugin
Echo the form using shortcode. Pick up the post data using wordpress init action.
shortcode output
{
//do something
echo "Successfully Subscribed"
}
else
{
?>
<form method="post" action="">
<input type="email" name="email">
</form>
<?php
}
plugin file
function subscribe()
{
if(isset($_POST["email"]))
{
//do something
$form_response = true;
}
}
add_action("init", "subscribe");
init action is fired after wordpress loads(i.e., finishes registering actions and filters) and before producing output. This would be a nice place to handle the POST data.
A plugin shortcode could also have output the same code as for single page but I prefer this method as its more profession way of doing it.
Leave a Reply