In Previous Tutorial We Have Created Template For Custom Form. Now add functionality for Validate data and Add data in database.
First we add functionality for validate data inserted in form .
- To do this create a new js file custom.js with functionality for validation.
- Put below code in it.
function form_validation(){
if( jQuery("#form_title").val() == "" ){
alert("Enter Form Title");
jQuery("#form_title").focus();
return false;
}
if( jQuery("#form_description").val() == "" ){
alert("Enter Form Description");
jQuery("#form_description").focus();
return false;
}
if( jQuery("#form_image").val() == "" ){
alert("Select Form Image");
jQuery("#form_image").focus();
return false;
}
if( jQuery("#form_type").val() == "" ){
alert("Enter Form Type");
jQuery("#form_type").focus();
return false;
}
if( jQuery("#form_author_name").val() == "" ){
alert("Enter Form Author");
jQuery("#form_author_name").focus();
return false;
}
}
After creating this file put it in js folder in your theme
You need to include this file to call this function.Put below code in your theme's function.php file
wp_enqueue_script( 'custom-js-script', get_template_directory_uri() . '/js/custom.js', array(), '1.0.0', true );
Add Data to Database
For this add below funtion to function.php file
add_action("init", "form_submit_fn");//Add Function
function form_submit_fn(){
if ( isset( $_POST['form_submit'] ) || wp_verify_nonce( $_POST['form_submit'], 'form_submit_flag' ) ) {
$form_title = $_POST["form_title"];
$form_description = $_POST["form_description"];
$form_image = $_POST["form_image"];
$form_type = intval( $_POST["form_type"] );
$form_author_name = $_POST["form_author_name"];
// Create post object
$my_post = array(
'post_title' => $form_title,
'post_content' => $form_description,
'post_status' => 'publish',
'post_type' => 'form'
);
// Insert the post into the database
$post_id = wp_insert_post( $my_post );
wp_set_object_terms( $post_id, $form_type, 'genre' );
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( "form_image", $post_id );
if ($attach_id > 0){
set_post_thumbnail($post_id, $attach_id);
}
update_post_meta( $post_id, "form_author", $form_author_name );
}
}
0 comments:
Post a Comment