Today, we will begin the mini-series on how to insert posts via the front end. We will be covering a variety of different aspects in this tutorial, beginning with form validation and inserting posts. So, let's get ready and begin!
Introduction
Our goal after completing this mini-series should allow the user to submit posts via the front end, along with editing and sending the post to the trash; all without being in the WordPress Dashboard. These methods can be used in either a theme or plugin and be very adaptable to achieve very advanced and complex submissions.
The demo and the download files are a stripped down theme which has been created for just the purposes of this tutorial.
So open up your favourite text editor and let’s begin!
Step 1 Creating a Form
We begin by creating a form which will allow the user to enter the details with regards to creating a post. As we are building this into a theme, let's begin by creating a new page template and let's call it template-insert-posts.php. We will then begin constructing our form, and inserting some labels and input fields for the post title and textarea for the body:
<form action="" id="primaryPostForm" method="POST"> <fieldset> <label for="postTitle"><?php _e('Post Title:', 'framework') ?></label> <input type="text" name="postTitle" id="postTitle" class="required" /> </fieldset> <fieldset> <label for="postContent"><?php _e('Post Content:', 'framework') ?></label> <textarea name="postContent" id="postContent" rows="8" cols="30" class="required"></textarea> </fieldset> <fieldset> <input type="hidden" name="submitted" id="submitted" value="true" /> <button type="submit"><?php _e('Add Post', 'framework') ?></button> </fieldset> </form>
What we have just created is a very simple form which has a text input for the user to enter the title and a textarea for the content of the post.
Now that we have our fundamentals set, we will need to perform some form validation to ensure that we are getting correct content and not having malicious attacks against our submissions.
Step 2 Form Validation
We will be using two different forms of validation. We will be using the jQuery Validation Plugin, along with traditional PHP validation. Let's begin with the jQuery side of validation first and initialise our validation script. We will ensure that we register and enqueue the scripts within our functions.php file. Along with this, we will create a blank JavaScript file where we will handle all of our custom jQuery; remember to register and enqueue this file for initialisation. This should look something like this:
// custom jquery wp_register_script( 'custom_js', get_template_directory_uri() . '/js/jquery.custom.js', array( 'jquery' ), '1.0', TRUE ); wp_enqueue_script( 'custom_js' ); // validation wp_register_script( 'validation', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js', array( 'jquery' ) ); wp_enqueue_script( 'validation' );
Great, we have registered and enqueued all of our necessary scripts. We will now open our custom jQuery file and begin initialising our jQuery Validation Plugin; we will open our blank JavaScript file and write the following line of code to create our jQuery Validation:
jQuery(document).ready(function() { jQuery("#primaryPostForm").validate(); });
All we have done here is get the ID of our form and apply the validate
method to this. Now that we have this in place, we will go back to our template-insert-posts.php file and ensure that we have put the required
class into the input fields which are required.
All the jQuery Validation is in place, let's move onto the PHP Validation.
Our validation should ensure that we enter a title, and if the jQuery Validation fails, then it will fall back to the PHP Validation. We do this by first creating a PHP variable to store the error message, and then create some conditional tests.
We initially test if the user has submitted the form, and then we test if our PHP error message variable is blank. We need to insert the following code which does this just above our <?php get_header(); ?>
:
<?php $postTitleError = ''; if ( isset( $_POST['submitted'] ) ) { if ( trim( $_POST['postTitle'] ) === '' ) { $postTitleError = 'Please enter a title.'; $hasError = true; } } ?>
Our PHP Validation is in place, we are going to ensure that the value we are submitting is the same value the user has entered, and we do this by inserting the following code into our postTitle
input field:
value="<?php if ( isset( $_POST['postTitle'] ) ) echo $_POST['postTitle']; ?>"
We also need to do the same for our text area but it works slightly differently; instead of setting a value, we insert the following code inside our postContent
textarea tags:
<?php if ( isset( $_POST['postContent'] ) ) { if ( function_exists( 'stripslashes' ) ) { echo stripslashes( $_POST['postContent'] ); } else { echo $_POST['postContent']; } } ?>
Finally, we need to ensure that we are outputting our error message, and we do this by checking if our error message variable is empty. If our variable is not empty then output the message else do not output anything. The following code achieves this:
<?php if ( $postTitleError != '' ) { ?> <span class="error"><?php echo $postTitleError; ?></span> <div class="clearfix"></div> <?php } ?>
Now that we have set up our form with validation we can move onto inserting the content into a post. Let's move on...
Step 3 Submitting a Post
We will now submit our form data into an actual post. We do this by using the WordPress function wp_insert_post
. This function allows us to insert posts, so we will be using this to our advantage.
We begin by first creating a variable to hold all of our different elements. You can define a whole bunch of different elements and you can read about in the WordPress Codex. Insert the following code, just below your form validation code:
$post_information = array( 'post_title' => wp_strip_all_tags( $_POST['postTitle'] ), 'post_content' => $_POST['postContent'], 'post_type' => 'post', 'post_status' => 'pending' ); wp_insert_post( $post_information );
The code we have just inserted creates an array and assigns values to the different elements. For the post_title
element, we POST our postTitle
value, and we POST our postContent
to our post_content
element.
We also set our post type to post
, as we will be submitting the default post type but you are able to pass any custom post type to this field. Finally we are setting the status of the post to be pending so the admin can confirm the post before publishing it.
We then run the function wp_insert_post
and pass our array with all our elements and the data assigned to them.
That's it! We are now able to add posts via the front end, but we are not finished yet. We have some security issues that we need to compensate. We begin by inserting a wp_nonce_field
. If you don't know what a nonce field is, the WordPress Codex explain it perfectly:
The nonce field is used to validate that the contents of the form came from the location on the current site and not somewhere else.
This will help us against any security issues and prevent any malicious attacks. All we have to do is insert the following code just before our submit button:
<?php wp_nonce_field( 'post_nonce', 'post_nonce_field' ); ?>
Along with this, we will edit our form validation to ensure that we are only submitting content once the nonce field has been confirmed that we are submitting the content from the website, we do this by replacing our validation conditional statement. Your final code with validation and submitting the data should be as follows:
if ( isset( $_POST['submitted'] ) && isset( $_POST['post_nonce_field'] ) && wp_verify_nonce( $_POST['post_nonce_field'], 'post_nonce' ) ) { if ( trim( $_POST['postTitle'] ) === '' ) { $postTitleError = 'Please enter a title.'; $hasError = true; } $post_information = array( 'post_title' => wp_strip_all_tags( $_POST['postTitle'] ), 'post_content' => $_POST['postContent'], 'post_type' => 'post', 'post_status' => 'pending' ); wp_insert_post( $post_information ); }
Finally, just for an extra we will set a redirect once the user has submitted the information, so that users can not press submit multiple times and keep entering the same data into our posts. We will do this on a very basic level.
As wp_insert_post
returns an ID we will use this to our advantage, and return the ID to a variable which we will use to ensure that we are not redirecting if no post was created.
We will do this by assigning our wp_insert_post
function to a variable, as follows:
$post_id = wp_insert_post( $post_information );
We then will run a conditional statement to only redirect if we have a post ID, then use the WordPress redirect
function and pass the home_url
to this. The code you will insert is as follows:
if ( $post_id ) { wp_redirect( home_url() ); exit; }
All done...
Conclusion
That's the basics and fundamentals on how to insert posts via the front end. We have covered a lot, by first creating a form, form validation and submitting our data into a pending post!
Within the next part, we will be digging a little deeper into editing and deleting posts via the front end, which gets a little more tricky but it can be very useful!
I would like to say a HUGE thank you for spending the time to read my tutorial, I hope it helped. Please feel free to leave comments and I will try my best to assist and answer them, if not you can always contact me directly through my website: www.VinnySingh.co or Twitter @VinnySinghUK
Stay Tuned For Part 2!
Comments