Review of Posting From Front End Form

Over the past three days we’ve accomplished quite a bit. First we set up a form to post from the front end. Once we had the form all set up, we dropped in some code to allow images to be uploaded with the form. And finally we added in the ability to use custom meta boxes on our form to collect additional information in custom fields for us to use. That’s a lot of code. Plus I had some difficulties with code that sometimes worked and sometimes did not. I got that all fixed. I thought it might be best to drop the full code I have in one post so that we can review it together.

So let’s take a look at the code. Now I’m pretty much just going to drop what I have here for you to look at it. I’m not going to spend too much time explaining it. If you have questions you can always go back to the original posts that are all linked above. So first off let’s take a look at the main form page. Now remember that I use a twenty ten child theme. So my code will reflect that. Your’s may be slightly different depending on what theme you use. If you recall I made a page template, kept in a basic loop, and added in my form and processing code. Here is the complete final results of that:

<?php
/*
Template Name: Rate Wine Form
*/
?>
<?php
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "new_post") {

	// Do some minor form validation to make sure there is content
	if (isset ($_POST['title'])) {
		$title =  $_POST['title'];
	} else {
		echo 'Please enter the wine name';
	}
	if (isset ($_POST['description'])) {
		$description = $_POST['description'];
	} else {
		echo 'Please enter some notes';
	}

	$tags = $_POST['post_tags'];
	$winerating = $_POST['winerating'];

	// ADD THE FORM INPUT TO $new_post ARRAY
	$new_post = array(
	'post_title'	=>	$title,
	'post_content'	=>	$description,
	'post_category'	=>	array($_POST['cat']),  // Usable for custom taxonomies too
	'tags_input'	=>	array($tags),
	'post_status'	=>	'publish',           // Choose: publish, preview, future, draft, etc.
	'post_type'	=>	'post',  //'post',page' or use a custom post type if you want to
	'winerating'	=>	$winerating
	);

	//SAVE THE POST
	$pid = wp_insert_post($new_post);

             //KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
	wp_set_post_tags($pid, $_POST['post_tags']);

	//REDIRECT TO THE NEW POST ON SAVE
	$link = get_permalink( $pid );
	wp_redirect( $link );

	//ADD OUR CUSTOM FIELDS
	add_post_meta($pid, 'rating', $winerating, true);

	//INSERT OUR MEDIA ATTACHMENTS
	if ($_FILES) {
		foreach ($_FILES as $file => $array) {
		$newupload = insert_attachment($file,$pid);
		// $newupload returns the attachment id of the file that
		// was just uploaded. Do whatever you want with that now.
		}

	} // END THE IF STATEMENT FOR FILES

} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM

//POST THE POST YO
do_action('wp_insert_post', 'wp_insert_post');

?>

<?php get_header(); ?>

		<div id="container">
			<div id="content" role="main">

<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>

				<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
					<?php if ( is_front_page() ) { ?>
						<h2 class="entry-title"><?php the_title(); ?></h2>
					<?php } else { ?>
						<h1 class="entry-title"><?php the_title(); ?></h1>
					<?php } ?>

					<div class="form-content">
						<?php the_content(); ?>

		<!-- WINE RATING FORM -->

		<div class="wpcf7">
		<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form" enctype="multipart/form-data">
			<!-- post name -->
			<fieldset name="name">
				<label for="title">Wine Name:</label>
				<input type="text" id="title" value="" tabindex="5" name="title" />
			</fieldset>

			<!-- post Category -->
			<fieldset class="category">
				<label for="cat">Type:</label>
				<?php wp_dropdown_categories( 'tab_index=10&taxonomy=category&hide_empty=0' ); ?>
			</fieldset>

			<!-- post Content -->
			<fieldset class="content">
				<label for="description">Description and Notes:</label>
				<textarea id="description" tabindex="15" name="description" cols="80" rows="10"></textarea>
			</fieldset>

			<!-- wine Rating -->
			<fieldset class="winerating">
				<label for="winerating">Your Rating</label>
				<input type="text" value="" id="winerating" tabindex="20" name="winerating" />
			</fieldset>

			<!-- images -->
			<fieldset class="images">
				<label for="bottle_front">Front of the Bottle</label>
				<input type="file" name="bottle_front" id="bottle_front" tabindex="25" />
			</fieldset>

			<fieldset class="images">
				<label for="bottle_rear">Back of the Bottle</label>
				<input type="file" name="bottle_rear" id="bottle_rear" tabindex="30" />
			</fieldset>

			<!-- post tags -->
			<fieldset class="tags">
				<label for="post_tags">Additional Keywords (comma separated):</label>
				<input type="text" value="" tabindex="35" name="post_tags" id="post_tags" />
			</fieldset>

			<fieldset class="submit">
				<input type="submit" value="Post Review" tabindex="40" id="submit" name="submit" />
			</fieldset>

			<input type="hidden" name="action" value="new_post" />
			<?php wp_nonce_field( 'new-post' ); ?>
		</form>
		</div> <!-- END WPCF7 -->

		<!-- END OF FORM -->
						<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
						<?php edit_post_link( __( 'Edit', 'twentyten' ), '<span class="edit-link">', '</span>' ); ?>
					</div><!-- .entry-content -->
				</div><!-- #post-## -->

				<?php comments_template( '', true ); ?>

<?php endwhile; // end of the loop. ?>

			</div><!-- #content -->
		</div><!-- #container -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>

So that form has code from all three tutorials in it. It has the basic post from front end form. It has the code in place for allowing image uploads. It also has the custom field meta box code in it. The next bit of code we need goes in functions.php. This is the bit for allowing the image uploads.

function insert_attachment($file_handler,$post_id,$setthumb='false') {
	// check to make sure its a successful upload
	if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

	require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	require_once(ABSPATH . "wp-admin" . '/includes/file.php');
	require_once(ABSPATH . "wp-admin" . '/includes/media.php');

	$attach_id = media_handle_upload( $file_handler, $post_id );

	if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
	return $attach_id;
}

That’s it for the posting bit. I’ll add in a couple more bits of code, the stuff you need for displaying the extra stuff in the form. For instance the images in my form will upload and attach to the post, and the last image becomes the featured image. But the images attached to the post are not set to display. Here’s the code that goes in your loop to actually display the images:

<div class="wineBottles">
<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
	foreach ( $attachments as $attachment ) { ?>
		<div class="wineImage">
			<span class="wineTitle">
		<?php echo apply_filters( 'the_title' , $attachment->post_title ); ?>
			</span>
		<?php the_attachment_link( $attachment->ID , false ); ?>
		</div>
	<?php }
}
?>
</div>

As I said before, there is some various css selectors added in there. You’ll need to swap them out, or define them in your css. I won’t be getting into styling stuff in this tutorial as that’s a matter of personal preference. Finally we need the bit of code for displaying the data from the custom field in the form. This also goes in your loop, wherever you want the data output. You’ll need to change this up to make use of your data however you need it, this is a very basic example:

				<div class="wineRating">
				<?php if( get_post_meta($post->ID, "rating", true) ): ?>
				<?php echo get_post_meta($post->ID, "rating", true); ?>
				<?php endif; ?>
				</div>

And that is all of it. Every bit of code I’ve used so far to get my post from front end form working properly. I hope this helps you out some. Now take this and run with it, you can do so much stuff once you understand how this all works.

UPDATE: @trusktr helped me out by leaving a comment over on the wordpress answers site. I haven’t had a chance to play with this yet, but wanted to get it up here asap for users playing around with this form. Trusktr reports that in the validation code at the top changing:

 isset ($_POST['description'])

 to

$_POST['description'] != ''

Solves our problems and stops the form from posting when it should not. If anyone messes around with this, let us know how it works out!