How to Create Custom form in Wordpress without plugin

How to create Custom form in wordpress without plugin:

Although while building a website with wordpress there are many wordpress plugins which can be used to create wordpress forms for wordpress website like wp_forms wp_forms,gravity forms  Gravity forms,ninja forms  Ninja forms. So you can use these wordpress plugins as well but I personally feels that it's easy to make any change in your code instead of changing wordpress plugins code.In this article we will see how to create custom wordpress form without plugin.

Clean Approach for creating custom wordpress form:

Keep only html code inside the wordpress form page
  • Keep all the css inside wordpress style.css file.
  • Keep PHP functions inside wordpress functions.phpif the core logic is separate from the appearance of the form than it is easy to maintain the code in long run. 
Putting the core logic, cosmetics and appearance in same page make it difficult to manage the code in long run.You can think of like you have to make changes in the core logic of the form or you want to change the appearance of the form then how difficult it will become to add the new core logic without disturbing the appearance or changing the wordpress website appearance without disturbing the core logic of that wordpress form.

How to edit code files in wordpress website.

For editing wordpress website code first login to admin portal of your website. just append wp-admin after the site url. for example if there is website with name ninjajobs than go to https://ninjajobs/wp-admin. On left side bar there will be a tab name appearance and from there go to them editor.

List of files will get shown up on the right side bar of wordpress website. Files mentioned above can be seen there click anyone of them to edit and create a custom form for the wordpress website. it's just so easy.



What is wordpress nonce field:

wp_nonce_field in wordpress website is use to verify that the data is coming from the intended wordpress form. wp_nonce_field are used in custom wordpress forms. it takes mainly two arguments one is action and other is name.

How to use Nonce in submit form:

Nonce_field is used to make sure that the form data has come from a particular form in the website.

<!--?php wp_nonce_field( 'wpshout-frontend-post','form-submit' ); ?-->

  • nonce_field_action is wpshout-frontend-post
  • nonce_field_name is form-submit

In the above example you can see that we have define wpshout-frontend-post as nonce_field. Whenever we are going to submit wordpress form, the nonce_field will get set in the request and we can check if a particular nonce_field is set in the request than only perform certian operation on database.

How to Verify if Nonce field is set in request:

 if( !wp_verify_nonce($_POST['form-submit'], 'wpshout-frontend-post') ) {		
        echo '<h3>Did not save because your form seemed to be invalid. Sorry</h3>';
        return;

You can use above code inside functions.php in wordpress website to check if a data has come from a particular web page. when form will get submitted than you can check in Post request if a nonce_field name exists or not. if it exists than the action name is matched to a correct action name. if both condition are true than perform other operation otherwise return.

Custom form for wordpress without plugin:

<div class="employee">
<input type="hidden" name="show_msg">

<form name="customer_details" method="POST" required="required" class="input-hidden">
Your Name: <input type="text" id="name" name="customer_name">
Your Email: <input type="text" id="email" name="customer_email">
Company: <input type="text" id="company" name="company">
Sex: <input type="radio" name="customer_sex" value="male">Male <input type="radio" name="customer_sex" value="female">Female
<textarea id="post" name="experience" placeholder="Write something.." style="height:400px;width:100%"></textarea>
<input type="submit" value="Submit">
<!--?php wp_nonce_field( 'wpshout-frontend-post','form-submit' ); ?-->
</form></div>
Above code is a sample submit form for wordpress website. nonce_field is defined in the form have action name as wpshout-frontend-post and nonce_field_name as form-submit. whenever the form get submitted than the php post attribute will have the nonce-filed parameter set in the request.
User can easily identify if a request has came from a particular wordpress form.

How To process output from submitted Wordpress form:
When a particular wordpress form get submitted then user have to do some kind of processing on the data submitted by wordpress form. like validating the data against a certain output, showing a success page if data get submitted to database. so for doing all these post processing of form data you can write a php function inside functions.php file that will be a cleaner approach for writing the code for wordpress website. There is a action hook template_redirect in wordpress which can be used for this purpose
  • template_redirect: This action hook gets automatically called just before rendering to any new page. so this is the good hook to use if you want to do any processing on data after submitting wordpress form and before showing the new success page. 
function wpshout_frontend_post() {
    wpshout_save_post_if_submitted();
}
add_action('template_redirect','wpshout_frontend_post', 2);
An action can be attached to a hook. add_action function of wordpress should be called to map the callback function with a hook. first create callback function and then mapp it to a hook.
the callback function will get executed when the mapped hook get called in wordpress.

add_action(string $hooks_name, callback $function_name, int $priority, int $accepted_args=1)

add_action method take 4 arguments
  • hooks_name: Name of the hook to which a callback function will be mapped
  • function_name: As the name suggest it will be the name of callback function you want to execute when a particular hook get triggered.
  • priority: It defines the priority of of the callback function. Function will get called in order of there priority. lower priority means function will get executed early.
  • accepted_args: Number of argument function accept

How to save form data in database from wordpress form:

Create a Table in the database: if you are using website hosting website like hostinger or godaddy then you can go to phpadmin page from there you can create a database with any given name.




Insert data in database from wordpress form: 
Wordpress provides a global $wpdb object which is instantiation of wpdb class in wordpress. wpdb object can be used inside php function for interacting with the website database. wpdb class has a function named query  query function takes one argument as a string. it takes the sql query user want to execute in the database. for example wpdb->query("insert into table employee(name, age) values('rahul', 30)").  if above sql query gets executed successfully than wpdb->query function will return the count of row it inserted and if it fail to execute sql query then it will return Null.
User should handle this error wisely. 

Things to remember while using wpdb->query:
  • Make sure that table exists in the data base before executing wpdb query
  • Make sure you are passing the right data type in the query. for example if the column type is varchar than make sure you are passing string and similarly integer for numbers.

How to show success page in wordpress website:

There is a function called wp_verify_nonce which is used in combination with wp_nonce_field. wp_nonce_field is used to add any action and wp_verify_nonce is used to check whether a given action is present in wordpress form data. wp_verify_nonce should be used in a php function define inside functions.php in wordpress. for simple functionalitybelow is the example code for that

  • wp_redirect: This wordpress function is used to redirect the output to some other page.Like showing the success message to a user on a new page. wp_redirect does not exits by itself so always make a exit call after calling wp_redirect in wordpress. wp_redirect takes first argument as the path of the page to which you want to re-direct user after a certain condition met. In below php code  user is getting re-directed to 'https://jobgetter.in/index.php/Interview-exp-success' so we have passed it as the first argument to wp_redirect function in wordpress.

PHP Code
   if( !wp_verify_nonce($_POST['form-submit'], 'wpshout-frontend-post') ) {		
        return;}
   wp_redirect('https://jobgetter.in/index.php/Interview-exp-success')


In above php code we are using wp_verify_nonce to check if the POST data has the nonce field 'form-submit'. if yes then it will go forward otherwise it will return and does not execute rest of the code. 
.
Below is the complete php function written inside functions.php in wordpress website.
Use it with the wordpress form data code provided above
function wpshout_save_post_if_submitted() {
    
     Check that the nonce was set and valid
    if( !wp_verify_nonce($_POST['form-submit'], 'wpshout-frontend-post') ) {		
        echo '<h3>Did not save because your form seemed to be invalid. Sorry</h3>';
        return;
    }

    // Do some minor form validation to make sure there is content
    if (strlen($_POST['interview-company']) < 3) {
		if ( !function_exists( 'add_settings_error' ) ) { 
           require_once ABSPATH . '/wp-admin/includes/template.php'; 
          } 
		$message='<h3>Please enter a cmpany name. Titles must be at least three characters long</h3>';
		add_settings_error( 'post error', 'post-err', $message, 'error' );
		settings_errors( 'post error');
       // echo '<h3>Please enter a title. Titles must be at least three characters long.</h3>';
        return;
    }
    if (strlen($_POST['interview-exp']) < 10) {
        echo 'Please enter content more than 100 characters in length';
        return;
    }

    // Add User Post to DB
    global $wpdb;
	$tablename=$wpdb->prefix.'interview_exp';
	require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
	
	$sql = "INSERT INTO $tablename (title,content,email,name) ";
    $sql.= "VALUES('".$_POST['company']."','".$_POST['experience']."','".$_POST['email']."','".$_POST['name']"')";

    $submit_post=$wpdb->query($sql);
    if ($submit_post){
		wp_redirect('https://jobgetter.in/index.php/Interview-exp-success');
		echo 'Saved your post successfully! :)';
	}
	else{
		echo 'Error Submittig Post';
		echo $wpdb->last_query;
	}
	
}
function wpshout_frontend_post() {
    wpshout_save_post_if_submitted();
}
add_action('template_redirect','wpshout_frontend_post', 2);


Above is the code to submit form data to database in wordpress website. if a particular nonce_field is set the above function will get executed otherwise it will return.

Hope above post will be helpful for you.




how-to-add-php-code-in-wordpress-page

wp->results returning empty

Comments

Popular posts from this blog

Wordpress Wpdb->get_results()

How to add php code in wordpress page