how to create a form in wordpress without plugins

How to Create a Form in WordPress Without Plugins

Do you want to create a form in WordPress without using plugins? Forms are some of the most essential and used elements of a website, and there are several advantages of creating one without using plugins.

Why Create a Form in WordPress Without Plugins

There are many WordPress form plugins that you can use to create a form. But creating a form in WordPress without using plugins can be beneficial for several reasons:

  • Simplicity and lightweight: You avoid the additional overhead that comes with installing and maintaining plugins when you create a form without plugins. A simple form created with custom code can be more lightweight and efficient than one made using a plugin.
  • Customization: Building a form from scratch gives you complete control over its design and functionality. You can tailor the form to match your website’s specific needs and customize it accordingly.
  • Learning experience: Building a form without plugins can be a great learning experience for developers or users interested in improving their coding skills. You get to understand the underlying mechanisms of form handling and data processing.
  • Reduced dependency: You reduce your website’s reliance on external code by not relying on plugins. This can be useful if you want to minimize potential security risks or conflicts arising from using multiple plugins.
  • Performance: Custom-coded forms can provide better performance and speed for your website since they are lightweight compared to plugins. These custom forms only include the features you need and don’t have the additional functionalities provided by plugins that you may not utilize.
  • Flexibility: Custom forms offer greater flexibility for integrating with other parts of your website or custom post types. You can extend the form’s functionality based on your unique requirements.
    Sure, most of the plugins provide similar options using the shortcodes. But with the custom-coded forms, you can add them to specific locations on the website depending on how you want to display them.

How to Create a Form in WordPress Without Plugins

There are many types of forms that you can create in WordPress without using the plugins. But a contact form is one of the most essential and popular. So we will show you how to create a contact form in this tutorial.

Before we begin, we hope you have a basic understanding of programming since we will use scripting languages and markup languages like HTML and PHP. If you don’t have the required knowledge for it, we recommend you ask the assistance of a programmer to help you create a form.

To create a contact form in WordPress, you must create a contact page first. So let’s start with that.

1) Create a Page for the Form

Go to Pages > Add New from your WordPress dashboard.

This will open the page editor, where you can enter the page title and additional necessary description apart from the actual contact form. But if a form is the only thing you need on this page, we can go ahead and create the form directly.

2) Add HTML Code for Form in the Editor

Now, go to your Code editor by clicking on the Options (three vertical dots) > Code editor from the top left of your screen. Then, add an HTML code for the form in the editor. You can add the necessary form fields that you need based on the following code.

<form method="post">
  <label for="name">Name:</label>
<input type="text" name="name" required="">

<label for="email">Email:</label>
<input type="email" name="email" required="">

<label for="message">Message:</label>
<textarea name="message" required=""></textarea>

<input type="submit" value="Submit">
</form>

This code will help you create a simple contact form in WordPress. But you can easily modify it to create the form you want on your WordPress website.

After you add all the necessary form fields to the code, click on Publish or Update to save the changes on the contact page.

html code create a form in wordpress

If you preview the page, you can see the form you just created. But to make the form functional and extract data from it, you have to handle the form submissions as well. So we have to create a database for the form submissions after this.

form preview page create a form in wordpress

3) Create a Database Table for Form Submission

To create a database for form submissions, you can use a database management tool like phpMyAdmin. You can access it by logging into your cPanel. If you don’t have the necessary credentials, we recommend you contact your hosting service or the site owner.

Now, scroll down to the Database section and click on phpMyAdmin. This will open the phpMyAdmin dashboard, where you can see all your website’s databases.

Expand the table of your website database and scroll to the bottom of the page, where you can create a new database table. Here, enter the table name as “wp_contact_form_submission” and click on Go to create the new table.

Then, you have to enter the data fields for the form fields on the table’s columns and their types. According to the form that we just created, we’ll be adding the following column names and types:

  • name: TEXT
  • email: TEXT
  • message: TEXT
  • submission_time: DATETIME

Finally, click on Save to save changes in the database table.

We’ve named the database table based on the contact form we created. So you can change the table’s name depending on the form you initially created. Similarly, if you have used different form fields on your form, you can add the columns accordingly.

4) Add Code to Handle Form Submissions

After you create the database, you still have to add a set of codes to handle the form submissions in the theme functions file of your website.

But we recommend you backup your website before continuing since we will be editing some of the website’s core files. And any unintended changes might lead to further issues on your website. You can look at our detailed guide on how to backup a WordPress website if you need any help.

4.1) Access the Theme Functions File

Go to Appearance > Theme File Editor from your WordPress dashboard to access the theme functions file. You will find all the core theme files of your website here. Then select the Theme Functions (functions.php) file on the right side of your screen, where we will add the code.

form submission code page create a form in wordpress

4.2) Add the Code to the Theme File Editor

You can use the following to handle the form submission on your website. So add the following code at the end of the editor.

if ($_SERVER["REQUEST_METHOD"] === "POST") {
  $name = sanitize_text_field($_POST["name"]);
  $email = sanitize_email($_POST["email"]);
  $message = sanitize_textarea_field($_POST["message"]);

  // Add code to save the form data to the database
  global $wpdb;
  $table_name = $wpdb->prefix . 'contact_form_submissions';
  $data = array(
    'name' => $name,
    'email' => $email,
    'message' => $message,
    'submission_time' => current_time('mysql')
  );
  $insert_result = $wpdb->insert($table_name, $data);

  if ($insert_result === false) {
    $response = array(
      'success' => false,
      'message' => 'Error saving the form data.',
    );
  } else {
    $response = array(
      'success' => true,
      'message' => 'Form data saved successfully.'
    );
  }

  // Return the JSON response
  header('Content-Type: application/json');
  echo json_encode($response);
  exit;
}

This code will store the entered form data from the form to the form submission database table we just created. We’ve also included a JSON response to ensure that you’ve added the correct database table names and fields on your form when you edit the code. You can remove it after the form data are successfully stored on the database.

Just click on Update File after you have made all the necessary changes to the code.

5) Display Form Submissions on your Dashboard

After the form data are stored in the database, you can create your dashboard menu to view the form submissions. So we’ll include a code to display it as well.

You can add the following code to the theme functions file (funtions.php), just like in the previous step.

function display_contact_form_submissions_page() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'contact_form_submissions';
  $form_data = $wpdb->get_results("SELECT * FROM $table_name WHERE name <> '' AND email <> '' AND message <> '' ORDER BY submission_time DESC", ARRAY_A);

  ?>
  <div class="wrap">
    <h1>Contact Form Submissions</h1>
    <table class="wp-list-table widefat fixed striped">
      <thead>
        <tr>
          <th>Name</th>
          <th>Email</th>
          <th>Message</th>
          <th>Submission Time</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($form_data as $data) : ?>
          <tr>
            <td><?php echo esc_html($data['name']); ?></td>
            <td><?php echo esc_html($data['email']); ?></td>
            <td><?php echo esc_html($data['message']); ?></td>
            <td><?php echo esc_html($data['submission_time']); ?></td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
<?php }

function register_contact_form_submissions_page() {
  add_menu_page(
    'Contact Form Submissions',
    'Form Submissions',
    'manage_options',
    'contact_form_submissions',
    'display_contact_form_submissions_page',
    'dashicons-feedback'
  );
}
add_action('admin_menu', 'register_contact_form_submissions_page');

Once again, click on Update File after you paste and edit the code according to the form and database table you created.

Now if you go to your WordPress dashboard, you will be able to see a “Contact Form Submissions” menu. This will display all the form submissions of the form you initially created.

display form submissions page create a form in wordpress

Debug Options to Display Form Submissions

If you cannot see the form data, we recommend you add a code for debug output and SQL query on the code. You can add the codes var_dump($form_data); and var_dump($wpdb->last_query); respectively after the query.

So the code may look something like this:

function display_contact_form_submissions_page() {
  global $wpdb;
  $table_name = $wpdb->prefix . 'wp_contact_form_submissions';
  $form_data = $wpdb->get_results("SELECT * FROM $table_name ORDER BY submission_time DESC", ARRAY_A);

  var_dump($form_data); // Debug output
  var_dump($wpdb->last_query); // Debug SQL query

  ?>
  <!-- Rest of the code... -->
  <?php
}

Based on the debug report, you can edit the codes further to ensure the form data are displayed correctly. But you can also go through the points in the next section to ensure there hasn’t been any error on the code you used.

Essential Considerations for Creating an Efficient Custom Form

Here are some factors you should consider while editing the codes to create your custom form. They can be helpful if you come across any errors during the process.

  • Check the database: Ensure that the form data is saved correctly in the correct table. For this tutorial, it’s the ‘wp_contact_form_submissions’ table.
  • Check for errors: Check your PHP error logs or enable error reporting to see if there are any errors related to the form submission or the display of data. Errors may provide clues about what might be going wrong.
  • Check the form submission process: Ensure that the form data is being submitted correctly and that the PHP code for saving the form data executes without errors. Check if the form data is being passed correctly to the PHP code when the form is submitted.
  • Verify table name: Double-check that the table name used in the ‘display_contact_form_submissions_page()’ function matches the actual table name in the database. Ensure it is ‘wp_contact_form_submissions’ or adjust the table name according to your database table.
  • Clear Cache: If you are using any caching plugins or server-side caching, clear the cache to ensure you view the latest data.
  • Permissions: Make sure the user role you are logged in has the ‘manage_options’ capability to access the custom admin page. This capability allows administrators to access the page by default.

We have mentioned a set of codes for you to create a contact form in WordPress. But you must edit the codes if you want to make any other form or an alternative form with different data fields. So the above points can also be helpful for you to create your custom form on WordPress.

Conclusion

This is how you create a form in WordPress without using plugins. You can create forms using plugins too. However, creating a custom-coded form has a lot of advantages if you have a basic understanding of programming.

You can easily create a form with the basic sets of codes we’ve included in this tutorial. To summarize, here are the basic steps to build an effective one:

  • Add the code for the form on the page editor
  • Create a database for form submissions
  • Add necessary codes to handle form submissions and display them

We hope you can now confidently create a form on your website using the codes mentioned in this tutorial. You can edit them to include additional form fields, depending on your needs. If you encounter any issues, we’ve even added some debug options and factors to consider while building a custom code on WordPress.

So, have you ever tried creating a form in WordPress without a plugin?

Do let us know in the comments below.

In the meantime, feel free to look at the following articles to help you improve and customize your WordPress website.