Create Posts from WordPress Front-End

Date Posted: June 29, 2015, 10:15 am


In this tutorial I am going to discuss how to insert posts via the front end of your WordPress blog. This tutorial will also cover some validation techniques, setting the post as “pending”, and email notification when a new post is created. So let’s begin!

First, you would want to create a new page, let’s call it “Add Topic” with a slug of “add-topic”. Make sure that your permalink settings it set to “/%postname%/”

Next is to Log on to your FTP then navigate to your current theme’s folder and create a PHP file: page-add-topic.php. Test this page, it should show a blank white screen.

Now we are ready to add some code to this page, open page-add-topic.php using your favorite code editor. Create the header and the footer functions:

1
2
3
<?php get_header(); ?>
// HTML code goes here
<?php get_footer(); ?>

Create the form

Within the get_header and get_footer function, add the code bellow:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<div class = "content">
    <div class = "topic-submit">
        <?php echo $msg ? $msg : ''; ?>
    </div>
    <form method = "post">
        <div class = "form-group">
            <label class = "" for = "topic_title"><?php _e('Topic Title'); ?>*</label>
            <input type = "text" name = "topic_title" class = "form-control" value = "<?php echo $_POST['topic_title'] ? $_POST['topic_title'] : ''; ?>" />
        </div>
        <div class = "form-group">
            <label class = "" for = "topic_description"><?php _e('Topic Description'); ?>*</label>
            <textarea class = "form-control" name = "topic_description" rows= "15" ><?php echo $_POST['topic_description'] ? $_POST['topic_description'] : ''; ?></textarea>
        </div>
        <div class = "form-group">
            <label class = "" for = "topic_email"><?php _e('Your Email'); ?>*</label>
            <input type = "text" name = "topic_email" class = "form-control" value = "<?php echo $_POST['topic_email'] ? $_POST['topic_email'] : ''; ?>" />
        </div>
        <br class = "clearfix" />
        <input type = "submit" name = "topic_submit" class = "btn btn-default" />
    </form>
</div>

The “topic-submit” div container is where we will be outputting any error or success messages

Ok now that we have our form, we need to code the server side. Just before the get_header(); function, insert the following PHP code:

1
2
3
4
if (isset($_POST['topic_submit'])) {
// Sanitize the form fields here
// Create validation here
}

Sanitizing the Form Fields

To be sure that our visitors are submitting valid data and not some script or anything else that can harm our site, we need to sanitize the form fields:

1
2
3
4
// Sanitize the form fields here
$topic_title = sanitize_text_field($_POST['topic_title']);
$topic_description = wp_strip_all_tags($_POST['topic_description']);
$topic_email = sanitize_text_field($_POST['topic_email']);

We are simply passing all posted data to the sanitize_text_field function. The wp_strip_all_tags function sanitizes and strip all html tags from any input data that is why we no longer have to use sanitize_text_field with it.

Validation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Create validation here
if( empty( $topic_title ) ) {
    $msg .= '<p class = "post-error">Please enter a title</p>';
} else if ( empty( $topic_description )) {
    $msg .= '<p class = "post-error">Please enter a description</p>';
} else if ( empty( $topic_email )) {
    $msg .= '<p class = "post-error">Please enter your email address</p>';
} else if ( ! is_email( $topic_email )) {
    $msg .= '<p class = "post-error">Please enter a valid email</p>';
} else {
    // Insert the page to the database
   
    // Save a copy of the user's email to our database
   
    // Send an email notification to the admin email
}

In the code above, we are simply validating the input fields if they are empty and if the email address is of the right format.

You can test the form right now by navigating to the page ( ex. http://example.com/add-topic ) to see the form and the validation in action.

Inserting to the Database

Add the following code on the ELSE block:

1
2
3
4
5
6
7
8
9
10
// Insert the page to the database
$topic_data = array(
    'post_title'    =>  wp_strip_all_tags( $topic_title ),
    'post_content'  =>  implode( "\n", array_map( 'sanitize_text_field', explode( "\n", $topic_description ) ) ),
    'post_status'   =>  'pending',
    'post_author'   =>  1,
    'post_type'     => 'post'
);

$post_id = wp_insert_post( $topic_data );

Notice that we are setting post_status to “pending”, that way the admin can review the post before it appears on the site. Change the “post_type” value if you want to associate this new post with another post type. Make sure to replace “post_author” value with the admin user ID. If you are dealing with logged in users then it’s best to use the global $current_user variable then set the post author value to: “$current_user->ID” without the double quotes.

We then add the codes that will save the user’s email to our database for later use and also notify the admin email about the new post that is awaiting his/her approval:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
if( $post_id ){
    // Save a copy of the user's email to our database, you can remove this if you are dealing with logged-in users.
    update_post_meta( $post_id, 'topic_author', $topic_email );
   
    // Send an email notification to the admin email
    $from = 'info@example.com';
    $headers = 'From: Example.com <"' . $from . '">';
    $subject = "New topic awaiting approval";
   
    ob_start();
    ?>
   
    <p>A new topic is awaiting your approval, <a href = "<?php echo get_permalink( $post_id ); ?>">click here to review the topic</a></p>
    <p><br /></p>
    <p><a href = "<?php echo home_url(); ?>">carlofontanos.com</a></p>
   
    <?php

    $message = ob_get_contents();
   
    ob_end_clean();

    wp_mail(get_option('admin_email'), $subject, $message, $headers);
   
    $msg = '<p class = "post-success">Your topic has been submitted and is now awaiting for approval.</p>';
}

Feel Free to change and design the HTML contents above.

Test the Form

You now have a front-end form that includes validation and email notification, go ahead and test it!. You can style the error or success colors to have green and red background, your choice!.

Challange

Use JavaScript to validate the form fields then use AJAX to insert the data to the database.

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me