Today, we will be continuing with our mini-series on inserting posts via the front end, but in this part we will be exclusively looking into how to manage custom meta fields which we may have within our post type. So, let's get ready and begin!
Introduction
We are now in part 3 of our mini-series, and if you have not read the other two parts then I advise you do because we will be picking up from where we left off. 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 trash; all without being on the WordPress Dashboard. These methods can be used in both 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 Inserting Custom Meta Box
Let's begin by first creating a folder called include, in this folder we will create a file called post-meta.php. We will be creating our custom meta box inside of this file. I will be going through this fairly quickly but if you want to read about all the wonders you can achieve with custom meta boxes, Tammy Hart wrote an amazing tutorial series called Reusable Custom Meta Boxes.
Inside of our post-meta.php, we will create a prefix to ensure that we have a unique identifier for all of our fields, also we will begin by creating an array to hold all of our information to create a custom meta box. The following code is for creating an ID for the custom meta box, setting a title, where the meta box will appear (which post type), and the fields which it will have:
// Field Array $prefix = 'vsip_'; $vsip_post_meta_box = array( 'id' => 'vsip-post-meta-box', 'title' => __('Custom Meta', 'framework'), 'page' => 'post', 'context' => 'normal', 'priority' => 'high', 'fields' => array( array( 'name' => __('Custom Input One: ', 'framework'), 'desc' => __('Enter your custom meta 1', 'framework'), 'id' => $prefix.'custom_one', 'type' => 'text' ), array( 'name' => __('Custom Input Two: ', 'framework'), 'desc' => __('Enter your custom meta 2', 'framework'), 'id' => $prefix.'custom_two', 'type' => 'text' ), ) );
Next, we will be creating our meta box and we do this by creating a function. Inside this function we will be using the WordPress function: add_meta_box
.
The following code displays how we created our meta box, along with using the action hook add_meta_boxes
:
// Custom Meta Box add_action( 'add_meta_boxes', 'vsip_project_add_meta'); function vsip_project_add_meta() { global $vsip_post_meta_box; add_meta_box($vsip_post_meta_box['id'], $vsip_post_meta_box['title'], 'vsip_display_post_meta', $vsip_post_meta_box['page'], $vsip_post_meta_box['context'], $vsip_post_meta_box['priority']); } // END OF Function: vsip_project_add_meta
Now that we have created our meta box, along with having all the fields set with the information we want to store, we need to display our meta box. We do this by creating another function with the same name as our third parameter in our add_meta_box
function. In our case, we create a function called: vsip_display_post_meta
.
The following code gets each field inside of our array that holds all of our information and checks the type of field it is and outputs the correct field type:
function vsip_display_post_meta() { global $vsip_post_meta_box, $post; // Use nonce for verification echo '<input type="hidden" name="vsip_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />'; echo '<table class="form-table">'; foreach ($vsip_post_meta_box['fields'] as $field) { // get current post meta data $meta = get_post_meta($post->ID, $field['id'], true); switch($field['type']) { // If Text case 'text': echo '<tr style="border-top:1px solid #eeeeee;">', '<th style="width:25%"><label for="', $field['id'], '"><strong>', $field['name'], '</strong><span style=" display:block; color:#999; line-height: 20px; margin:5px 0 0 0;">'. $field['desc'].'</span></label></th>', '<td>'; echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : stripslashes(htmlspecialchars(( $field['std']), ENT_QUOTES)), '" size="30" style="width:75%; margin-right: 20px; float:left;" />'; break; } } echo '</table>'; } // END Of Function: vsip_display_post_meta
We have created our custom meta box and displayed its content, all we have left to do is save the data once the user has inserted content for the fields. We do this by creating one final function which will save our data correctly. The code is as follows:
// Save Meta Data add_action('save_post', 'vsip_post_save_data'); function vsip_post_save_data($post_id) { global $vsip_post_meta_box; // verify nonce if (!isset($_POST['vsip_meta_box_nonce']) || !wp_verify_nonce($_POST['vsip_meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // check permissions if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($vsip_post_meta_box['fields'] as $field) { $old = get_post_meta($post_id, $field['id'], true); $new = $_POST[$field['id']]; if ($new && $new != $old) { update_post_meta($post_id, $field['id'], $new); } elseif ('' == $new && $old) { delete_post_meta($post_id, $field['id'], $old); } } } // END Of Function: vsip_post_save_data
Okay, I know we went through that very quick but the focus of this tutorial is how to manage the custom meta via the front end. Now that it's all out of the way and we have our custom meta box set up in our posts, we will continue into how to insert the fields into our insert post and to edit the custom meta fields.
Step 2 Editing Our Insert Posts
We will be editing our insert posts page to compensate for our newly added custom fields. Let's go and open up our template-insert-posts.php and insert some extra fields. As our custom meta fields are text fields, we will insert two extra text input fields into our form, as follows:
<fieldset> <label for="customMetaOne"><?php _e('Custom Meta One:', 'framework') ?></label> <input type="text" name="customMetaOne" id="customMetaOne" value="<?php if(isset($_POST['customMetaOne'])) echo $_POST['customMetaOne'];?>" class="required" /> </fieldset> <fieldset> <label for="customMetaTwo"><?php _e('Custom Meta Two:', 'framework') ?></label> <input type="text" name="customMetaTwo" id="customMetaTwo" value="<?php if(isset($_POST['customMetaTwo'])) echo $_POST['customMetaTwo'];?>" class="required" /> </fieldset>
We need to have it so when the user clicks 'Submit' it will insert the custom meta information into the appropriate fields. To do this, we need to use the WordPress function: update_post_meta
, what this function does is allow us to update the post meta, and we can only update the post meta once we have created a post and have an ID.
So, we will go where we are using the function: wp_insert_post
and just above our redirect link is where we will be inserting our custom meta.
The following code does our test to check if we have created a post, and then we use the update_post_meta
function and pass the post_id
to this function, along with the ID of the field we want to update, and finally the value from our form which we will posting to the meta box:
if($post_id) { // Update Custom Meta update_post_meta($post_id, 'vsip_custom_one', esc_attr(strip_tags($_POST['customMetaOne']))); update_post_meta($post_id, 'vsip_custom_two', esc_attr(strip_tags($_POST['customMetaTwo']))); // Redirect wp_redirect(home_url()); exit; }
That's it! We have created a custom meta box and we have updated our insert post form to ensure that we target these fields and they get saved correctly. Next, we will be moving onto how to the edit our custom meta.
Step 3 Editing Our Custom Meta
Now we need to be able to edit the custom meta via the front end, so we will begin by opening up our template-edit-posts.php and inserting our two new input fields which we added to our insert post form:
<fieldset> <label for="customMetaOne"><?php _e('Custom Meta One:', 'framework') ?></label> <input type="text" name="customMetaOne" id="customMetaOne" value="<?php if(isset($_POST['customMetaOne'])) echo $_POST['customMetaOne'];?>" class="required" /> </fieldset> <fieldset> <label for="customMetaTwo"><?php _e('Custom Meta Two:', 'framework') ?></label> <input type="text" name="customMetaTwo" id="customMetaTwo" value="<?php if(isset($_POST['customMetaTwo'])) echo $_POST['customMetaTwo'];?>" class="required" /> </fieldset>
Next, we need to retrieve our custom post meta of the specific post, we do this by using the WordPress function: get_post_meta
inside of our WordPress Loop. Scroll up to where we have our WordPress Loop and insert the following code just below where we got the information for our title and content.
$custom_one = get_post_meta($current_post, 'vsip_custom_one', true); $custom_two = get_post_meta($current_post, 'vsip_custom_two', true);
Now that we have the information of the custom post meta, we will now output the values of this into our input fields of our form. The following code is the updated version of the two custom meta fields which we inserted:
<fieldset> <label for="customMetaOne"><?php _e('Custom Meta One:', 'framework') ?></label> <input type="text" name="customMetaOne" id="customMetaOne" value="<?php echo $custom_one; ?>" class="required" /> </fieldset> <fieldset> <label for="customMetaTwo"><?php _e('Custom Meta Two:', 'framework') ?></label> <input type="text" name="customMetaTwo" id="customMetaTwo" value="<?php echo $custom_two; ?>" class="required" /> </fieldset>
As you can see from the code we just inserted, the values for both of our inputs are the variables of our custom meta which we created in our WordPress Loop, you may have noticed that it could output our fields but when we make changes no actual updates are made. This is because we haven't inserted the code to update the post once the user has clicked update.
Just the same way we added our post meta when inserting new posts, we will be doing this inside of our edit template, so add the following code:
if($post_id) { // Update Custom Meta update_post_meta($post_id, 'vsip_custom_one', esc_attr(strip_tags($_POST['customMetaOne']))); update_post_meta($post_id, 'vsip_custom_two', esc_attr(strip_tags($_POST['customMetaTwo']))); // Redirect wp_redirect(home_url()); exit; }
That's it! We have done it! We are now able to create a custom meta box, insert meta with the insert post via the front end along with editing the meta via the front end.
Conclusion
That's part 3 complete, you have done it! Well done, you are now capable of inserting posts, editing, and deleting posts via the front end, along with handling any custom meta you have.
That's the end of this series on Posting via the Front End, and I'm glad that you stayed with me whilst we went through our journey.
I would like to say a HUGE thank you for spending the time to read my tutorial series, I hope it helped. Please feel free to leave comments and I will try my best to assist and answer them. You can always contact me directly through my website: www.VinnySingh.co or Twitter @VinnySinghUK.
Comments