How to Add Front End Posting Functionality to WordPress by Building Your Own Plugin

Posted OnFeb 24, 2015     CategoryDevelopment     Comments4 comments

In this tutorial, we’ll add the ability to post from the front end of your WordPress website, by creating a plugin. We’ll walk you through, step by step, to make sure it’s easy to follow.

Create a form for posting from front end

We start by creating a plugin which will handle the post from the front end for us. To do this, go to wherever you have WordPress installed, then navigate to wp-content/plugins and create a folder called submitfromfront, then and add a file called submitfromfront.php as shown below

submit to front folder

In the file, add the following code

<?php
/*
Plugin Name: SubmitFromFront
Plugin URI: 
Description: This creates a form so that posts can be submitted from the front end
Version: 1.0
Author: a
Author URI: 
*/

class WPSubmitFromFront {

  protected $pluginPath;  
  protected $pluginUrl;  

  public function __construct() {  

    // Set Plugin Path  
    $this->pluginPath = dirname(__FILE__);  
    // Set Plugin URL  
    $this->pluginUrl = WP_PLUGIN_URL . '/submitfromfront';  
  }

  function handleFrontEndForm() {
    //Check if the user has permission to publish the post.
    if ( !current_user_can('publish_posts') ) {
        echo "<h2>Please Login to post links.</h2>";
        return;
    }

  $this->displayForm();
  
  }

  //This function displays the HTML form.
  public function displayForm() {
      ?>
  <div id ="frontpostform">
    <form action="" id="formpost" method="POST" enctype="multipart/form-data">

      <fieldset>
          <label for="postTitle">Post Title</label>
   
          <input type="text" name="postTitle" id="postTitle" />
      </fieldset>
   
      <fieldset>
          <label for="postContent">Content</label>
   
          <textarea name="postContent" id="postContent" rows="10" cols="35" ></textarea>
      </fieldset>
   
      <fieldset>
          <button type="submit" name="submitForm" >Create Post</button>
      </fieldset>

      <?php wp_nonce_field( 'front_end_new_post' , 'nonce_field_for_front_end_new_post'); ?>

    </form>
  </div>
        <?php
    }
}

$wpSubmitFromFEObj = new WPSubmitFromFront(); 

Here we have

  • Added a header for the plugin, including the name, description, version, and so on
  • Created a class WPSubmitFromFront in the constructor of the class
  • Initialized the plugin path and plugin url so that it can be used in various places in the plugin
  • Created the function handleFrontEndForm in which the first thing we check if the user has the permission to post or not
  • If the user does not have the permission we display a message to prompt the user to login
  • Then we call the function displayForm, in which we have the actual HTML code to display a form with the title and content field and the submit button
  • We also add the wp_nonce_field which adds a hidden field which helps us detect that the request is coming from our site itself and not from some unknown source

You can read more about wp_nonce_field at http://codex.wordpress.org/Function_Reference/wp_nonce_field.

Once you have done this you should be able to see the plugin in the plugin list in the admin section, activate the plugin before continuing.

activating submit to front

Styling the form

With our plugin activated, it’s time to style the form, you can feel free to do this yourself, or follow along with what we have below. For this example, first create the file submitfromfront.css in the submitffromfront directory, then add the CSS below.

#frontpostform  input, #frontpostform textarea { 
    padding: 9px; 
    border: dotted 2px #66FFFF; 
    outline: 0; 
    font: normal 13px/100% Verdana, Tahoma, sans-serif; 
    width: 200px; 
    background: #FFFFFF; 
    margin-top: 10px;

    } 
   
#frontpostform  textarea { 
    width: 500px; 
    height: 150px; 
    line-height: 150%; 
    } 
   
#frontpostform  input:hover, #frontpostform textarea:hover, 
#frontpostform input:focus, #frontpostform textarea:focus { 
    border-color: #3399FF; 
    } 
   
#frontpostform  label { 
    margin-left: 10px; 
    color: #999999; 
   
    } 
   
#frontpostform  button { 
    width: auto; 
    padding: 15px; 
    background: #617798; 
    border: 0; 
    font-size: 14px; 
    color: #FFFFFF; 
    float:right;
    margin-top: 10px;
 }

Now, in the class we created earlier — WPSubmitFromFront — add the following function:

function addStyles() {
        // Register the style for the form
        wp_register_style( 'submitform-style', plugins_url( 'submitfromfront/submitfromfront.css'));
        wp_enqueue_style( 'submitform-style' );
    }

And add the following line to the constructor:

//Add CSS for the form.
add_action('wp_enqueue_scripts', array($this, 'addStyles'));

In the above code we are hooking the function addStyles with the WordPress action wp_enqueue_scripts so that our scripts are also loaded. Then in function addStyles using the WordPress functions we register and add our styles in the file submitfromfront.css.

Create a short code to add the form on any page

With our form styled we can now display the form by associating it to a WordPress short code, so that particular short code can be added in any post or page to display the form on the front end.

To do that you will have to use add the following line to the constructor of the class WPSubmitFromFront:

//Add the short code
 add_shortcode('POST_FROM_FRONT', array($this, 'handleFrontEndForm'));

This uses the WordPress function add_shortcode to add the shortcode POST_FROM_FRONT and link it to the function handleFrontEndForm. Now you can create a page called Post from front and in the content as the short code as shown below:

using the post_from_front shortcode

Now if you go to the page you should be able to see the form as shown below

post from front form displaying on the front end

Validate the Fields

Once we have the form displaying, we will have to fetch the values in the form and do some validation. To do that, change the code for handleFrontEndForm as follows and also add the different function below

function handleFrontEndForm() {
  //Check if the user has permission to publish the post.
  if ( !current_user_can('publish_posts') ) {
    echo "<h2>Please Login to post links.</h2>";
    return;
  }

  if($this->isFormSubmitted() && $this->isNonceSet()) {
    if($this->isFormValid()) {
      $this->createPost();
    } else {
      $this->displayForm();
    }
  } else {
    $this->displayForm();
  }

}

function isFormSubmitted() {
  if( isset( $_POST['submitForm'] ) ) return true;
  else return false;
}

function isNonceSet() {
  if( isset( $_POST['nonce_field_for_front_end_new_post'] )  &&
    wp_verify_nonce( $_POST['nonce_field_for_front_end_new_post'], 'front_end_new_post' ) ) return true;
  else return false;
}

function isFormValid() {
    //Check all mandatory fields are present.
    if ( trim( $_POST['postTitle'] ) === '' ) {
      $error = 'Please enter a title.';
      $hasError = true;
    } else if ( trim( $_POST['postContent'] ) === '' ) {
      $error = 'Please enter the content.';
      $hasError = true;
    } 

    //Check if any error was detected in validation.
    if($hasError == true) {
      echo $error;
      return false;
    }
    return true;
}

function createPost() {
  
    }

In the above code of handleFrontEndForm we

  • Check if the form is submitted. That’s done in the function isFormSubmitted. It checks the submit button value is set in the POST variables array.
  • Then it checks if the Nonce is set which is done in the function isNonceSet, which uses the WordPress function wp_verify_nonce to verify the nonce.
  • Then we check if the form is valid with all the mandatory fields in the function isFormValid.
  • In isFormValid we are checking if postTitle and postContent is present otherwise it displays an error message.
  • If all validations are fine we will call the function createPost which currently does nothing but we will look at it in the next section.

Once you have added this code and try to click on create post without adding the title or the content and you will see the error as follows:

front end error message if the post is created without a title

Posting the Content and Creating the Post

Now, as we are done with the validations now we can create the post in the createPost function. Update the createPost function as below

function createPost() {

  //Get the ID of currently logged in user to set as post author
  $current_user = wp_get_current_user();
  $currentuserid = $current_user->ID;

  //Get the details from the form which was posted
  $postTitle = $_POST['postTitle'];
  $contentOfPost = $_POST['postContent'] ;
  $postSatus = 'publish'; // 'pending' - in case you want to manually approve all posts;

  //Create the post in WordPress
  $post_id = wp_insert_post( array(
    'post_title'        => $postTitle,
    'post_content'      => $contentOfPost,
    'post_status'       => $postSatus , 
    'post_author'       => $currentuserid
      
  ));

}

In the function createPost we

  • Use the WordPress function wp_get_current_user to get the current users ID which will be set as the author
  • Use the WordPress function wp_insert_postm to which we pass the title and the content of the postm which will create the content of the post

Now if you create a post using our form you should see the new post as shown below

successfully created post with our front end form

Conclusion

That’s it! You’ve now created a plugin that handles adding front end posting capacity to a WordPress website. You can use this as a base for future development, too, styling it more in line with your current WordPress theme, which could be done by simply changing the classes and IDs of the HTML elements, or even go as far as to add some JavaScript validation to the form.

If you’re interested, you can find the code for this plugin on GitHub

4 comments

Comments

  1. Sam

    Is there a way to add custom fields to the form? Like a URL field or a WISYWYG content area? That would be so useful.

    Also, is there a way to add make the form only output posts in a certain post format?

    1. Aaron Osteraas Article Author

      Hi Sam,

      You could add a URL field to the form, but how you do that depends on what you want WordPress to do with that URL.

      As a WYSIWYG editor, yes, it’s actually pretty easy to do as well with a function called wp_editor

  2. jam

    Will this work for just logged in users only as I just want buddypress users posting.

    Also what if you want the option to be able to add featured images?

    Is there a way to grab pieces from the backend eitors and embed them nto a page on wordpress such as the media up-loader/ featured image upload title and content editors from the back end and stick it on a page instead so that when these things are updated by wordpress it automatically updates on your frontend too.. so you are not vulnerable to exploits?

    Thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *

Send this to friend