Posting via the Front End: Inserting

Posting via the Front End: Inserting

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Intermediate
  • Estimated Completion Time: 30 mins / 1 Hour
This entry is part 1 of 3 in the series Posting via the Front End

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!


Other parts in this series:Posting via the Front End: Editing and Deleting
Tags: front end
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://shabushabu.eu Boris

    Just looking through your code, and there are some mistakes that should not be in a tutorial. For one, the use of esc_attr() and the lack of esc_textarea() are the most obvious. They’re meant for use within a html attribute, like value or within a textarea element, not to escape the data before saving it to the database.

    The code for the saving of the data should not be a part of the template. Rather, create a function, attach it to the init hook and place the whole thing in your functions.php file.

    post-type should be post_type and you don’t end up using the $postTitle variable in the end.

    • Adam

      WAW… you were quite taffy here… Anyway thanks to @Vinny Singh for this tutorial and thank you @Boris for the corrections.

      Ps. @Boris, have a look at the logo here “http://shabushabu.eu/wp-login.php” it needs to be fixed. ;-)

      • http://shabushabu.eu Boris

        @Adam
        My tone might have been slightly too harsh, but then, maybe not.

        Not sure if you heard about the latest discussions about bad code in themes? The biggest example came from a tutorial that many theme authors on ThemeForest use, where the the_content filter gets removed by a theme, just so column shortcodes (that have no place whatsoever to be in a theme in the first place) would work. This obviously would screw with plenty of plugins.

        It just shows that people do follow tutorials on large sites like the tutsplus network and people who don’t know any better will be using the above code in themes and plugins. The code above only works because the default post_type argument comes into play. If you wanted to adjust the form to submit a movie post type, it wouldn’t work anymore. That’s just a typo, though, so easily fixed and not that important. The use of the esc_* functions, though, is.

        • http://vinnysingh.co/ Vinny Singh
          Author

          @Boris

          Thanks firstly for giving the criticism and pointing out the small bugs I have made by mistake, These will be fixed and the Tutorial will be updated to fix these. I did manage to get a quick overview with the discussion on ThemeForest with the regards to Theme Developments putting functionality inside Themes when essentially it should be within Plugin’s.

          This Tutorial is designed to give a very quick insight to how to Insert Posts via the Front End, and if used in Commercial practice the User should have a more in depth knowledge and this should really be implemented inside of a Plugin and have the form outputted as a shortcode, but I wanted to provide the beginner users to get a feel of what can be done with WordPress.

          The Tutorial will be updated to fix the bugs! Thanks for reading guys and feedback! Much Appreciated.

          • http://shabushabu.eu Boris

            Thanks for updating the tutorial. Unfortunately, it’s not enough. You still need to use esc_attr() and esc_textarea() within the form. Even a quick insight needs to teach the basics and the use of these funcions, together with esc_url(), etc, are very much a part of that. A quick explanation of why it is important would go a long way for beginners to understand why it is important to use these functions.

          • http://vinnysingh.co/ Vinny Singh
            Author

            Should be all up to scratch now :)

          • http://www.facebook.com/lorelei.carson Lorelei Carson

            Thanks Vinny, couldn’t find this set of functions anywhere else. Appreciate it.

    • http://maorchasen.com Maor Chasen

      Strongly agree with Boris. That’s a misuse of esc_attr(). Also, there is a some use of PHP’s native trim(), which is quite not useful in this case since wp_insert_post() handles all of that automatically for us using sanitize_post().
      I strongly recommend you, Vinny, to read this section on the Codex. As you can see, there is no need for sanitizing or validating.
      Cheers!
      ~ Maor

      • http://sanjaykhemlani.com/how-create-article-website-design-photoshop/ sanjay

        Good call Boris! Maybe Vinny can correct these so newbies won’t use the wrong code, plus it’ll help the coding standardization.

      • http://vinnysingh.co/ Vinny Singh
        Author

        Thanks for noticing this Maor, I have fixed this :)

  • Kevin

    This is a great tutorial! I always wanted to see how to expand WordPress in other ways than just a standard blogging system!

    Thanks for this! Will be waiting for the next part!

  • Pingback: Add post from front end in WordPress « Tech Snippets

  • http://www.pengunjungblog.com/belajar-seo/ syaiful bahri

    Hi, Vinny! This is a great tutorial!! But, I stiil confuse about this function can use for handling my guest blogger in my wordpress blog?

  • http://wpthemesdaily.com/ Robert

    Thank you for this tutorial. Now I can get rid of ugly and heavy contact form plugins :)

  • http://jermainehercules.com jermaine

    Nice tutorial, I have one question can this method be used for custom post type more specific inserting media into a certain page gallery.

    A client ask for this and I had to tell them I don’t know how to do it yet.

    • http://vinnysingh.co/ Vinny Singh
      Author

      Yes, You are able to Insert Media via the Front End…I will be covering more in this Series and It will give you a better insight on to how to achieve this.

  • http://ruturaaj.com Ruturaaj

    This tutorial is nice and I liked that JQuery validation stuff! :-) I can already see this article is a part of series of articles. I hope sometime down the line, you will cover the Custom Meta fields in Front end form. Like, I’ve some custom meta boxes for my Custom Post Type; I’m not sure how to implement those with Front end Form. Perhaps update meta has the answer, but I will wait for your text on this issue.

    • http://vinnysingh.co/ Vinny Singh
      Author

      Hello Ruturaaj,

      We will be covering this in a later Series :) be sure to check it out :)

  • http://www.teamworksdesign.com Rob

    Is there going to be anything on user posts regarding this? I.e a new user sets up an account and is able to post but is only able to edit/delete their own posts. At the moment everyone is able to post and edit/delete anyone else’s posts.

    I’ve created something similar but would love to see how someone else does it.

  • http://www.eagletheme.com Eagle

    Thanks for this tut.

  • Pingback: Monday Afternoon WordPress Link Round-Up | HostNine Company Blog

  • http://tibesar.com Marcus Tibesar

    I am not able to implement your front-end Post form – its a bit too complex for me I’m afraid.

    Are you going to create a plug-in for this?

    Thank you for increasing the functionality of WordPress :-)

    Marc

    • http://28inch.co.uk 28inch

      If its too difficult for you, give a try for the P2 theme from automattic.

      http://p2theme.com/

  • Pingback: วิธีสร้าง Wordpress Plugin โพสเนื้อหาผ่านหน้าเว็บไซต์ | JDesign's Blog

  • Pingback: Posting via the Front End: Inserting | ThemeMountain

  • ZacEckstein

    I’ve got this code working, but for some reason it is creating two duplicate posts when the form is submitted. Any reason why this might be happening?

  • ZacEckstein

    I’ve got everything working except the redirect part. If I take that out, the form works fine (it submits the information) but doesn’t go to another page. I’ve tried multiple methods of redirecting and can’t seem to get it working. Any advice?

  • http://twitter.com/remicorson Rémi Corson

    Hi, thanks for the tutorial. Just to let you know that you wrote ‘post-type’ instead of ‘post_type’ in your query in the download file.

    • http://wp.tutsplus.com/ Japh

      Hi @twitter-78355893:disqus, can you point out where please? I can’t find “post-type” anywhere in this post.

      • http://www.facebook.com/ConnorM1995 Connor Miles

        Hello
        i loved the tutorial followed along ’till the end and everything works
        fine apart from the edit link. when i click on edit it takes me to the
        actual post page. so i also downloaded the source files and added as a
        new theme and its still taking me to the post page and not the edit
        page.

        Hope you can help cheers

      • Johan Nilsson

        @JaphThomson:disqus (and other users that use this tutorial): In template_insert_post.php,
        $post_information = array(
        ‘post_title’ => esc_attr(strip_tags($_POST['postTitle'])),
        ‘post_content’ => esc_attr(strip_tags($_POST['postContent'])),
        ‘post-type’ => ‘post’,
        ‘post_status’ => ‘pending’

        ***
        so “post-type” has to be changed to “post_type” if you want to change to a custom post type that you created.

        • http://wp.tutsplus.com/ Japh

          Thanks, @Johan (and @Remi of course!). Found and fixed now :)

  • http://www.facebook.com/ConnorM1995 Connor Miles

    Hello i loved the tutorial followed along ’till the end and everything works fine apart from the edit link. when i click on edit it takes me to the actual post page. so i also downloaded the source files and added as a new theme and its still taking me to the post page and not the edit page.

    Hope you can help cheers

  • Adal Bermann

    Do you happen to know how to set a specific post-format for the post being submitted?

  • Julesman

    Thanks for this tutorial. I’m trying to have the form and the post output on the same page. It seems to work fine with one problem. Youtube and Vimeo videos don’t load when the page refreshes after submittion, but do when I refresh the page again manually. Any thoughts on this would be appreciated as this front end post method seems to be the most efficient and I’d rather not use a plugin. Thanks.

  • http://twitter.com/mreonet Emre Caglar

    i implemented this tutorial everything is ok now thanks to you but i have one big problem. Everyone can edit all of the posts. As on demo website admins can just change the post i would like to have something that users can also change/delete their own post. Also just lists current user’s posts? Can you update the code or give us instruction to do it . Thanks again

  • Pingback: links | General