here’s a little example page template I put together that will let users add a new testimonial as a draft. To make it a little prettier, you could move the add_testimonial_from_form() function to your functions.php
<?php
function add_testimonial_from_form( $post_array )
{
$required_fields = array( 'name', 'email', 'testimonial' );
foreach( $required_fields as $field_name ){
if( ! array_key_exists( $field_name, $post_array ) || empty( $post_array[ $field_name ] ) )
return new wp_error( $field_name, 'Required field is missing.' );
}
# check email
if( ! filter_var( $post_array['email'], FILTER_VALIDATE_EMAIL ) )
return new wp_error( 'email', 'Email is invalid.' );
# check url if it's set, it's not required
if( isset( $post_array['url'] ) && ! empty( $post_array['url'] ) ){
if( ! filter_var( $post_array['url'], FILTER_VALIDATE_URL ) )
return new wp_error( 'URL', 'URL is invalid.' );
else
$url = $post_array['url'];
}
else
$url = false;
$new_post = array();
$new_post['post_title'] = esc_attr( $post_array['name'] );
$new_post['post_content'] = esc_attr( $post_array['testimonial'] );
$new_post['post_status'] = 'draft';
$new_post['post_type'] = 'testimonial';
if( ! is_wp_error( $new_post_id = wp_insert_post( $new_post ) ) )
{
# insert meta
## email
add_post_meta( $new_post_id, 'tbtestimonial_company_email', $post_array['email'] );
## company
if( isset( $post_array['company'] ) && ! empty( $post_array['company'] ) )
add_post_meta( $new_post_id, 'tbtestimonial_company', esc_attr( $post_array['company'] ) );
## url
if( $url ) add_post_meta( $new_post_id, 'tbtestimonial_company_url', $url );
# show user notice
printf( '<div class="updated">Testimonial Added and is awaiting review</div>' );
}
}
# template name: add testimonial
get_header();
# check for new testimonail and add it if present.
if( isset( $_POST['new_testimonial'] ) && is_array( $_POST['new_testimonial'] ) && count( $_POST['new_testimonial'] ) > 0 ){
if( is_wp_error( $error = add_testimonial_from_form( $_POST['new_testimonial'] ) ) )
printf( '<pre class="debug">%s</pre>', print_r( $error, 1 ) ); # dump error message
}
?>
<section id="content-wrap">
<form action="" method="post">
<p>
<label for="author-name">Your Name</label>
<input name="new_testimonial[name]" id="author-name" size="40">
</p>
<p>
<label for="author-email">Email Address</label>
<input name="new_testimonial[email]" id="author-email" size="40">
</p>
<p>
<label for="author-company">Company</label>
<input name="new_testimonial[company]" id="author-company" size="40">
</p>
<p>
<label for="author-url">Website URL</label>
<input name="new_testimonial[url]" id="author-url" size="40">
</p>
<p>
<label for="author-testimonial">Testimonial</label>
<textarea name="new_testimonial[testimonial]" id="author-testimonial" cols="100" rows="5"></textarea>
</p>
<p>
<input type="submit" value="Submit" />
</p>
</form>
</section>
<?php get_footer();