-1

I am currently doing it like this and I know that this isn't the right way.

I have 2 plugin files which will be named as index.php and process.php.

index.php will show the form while process.php will process the form.

In index.php I have the following code:

<?php 
/* 
Plugin Name: My Plugin
Plugin URI: https://wordpress.org/plugins/ 
Description: Just another plugin.
Version: 1.0.0 
Author: Author Name
Author URI: https://wordpress.org/plugins/ 
*/ 

add_shortcode('my_form_shortcode', 'my_form'); 

function my_form_content() {
  echo "
    <input type='text' id='my-field'>
    <button type='button' id='my-button'>Submit</button>
    <script>
      $('#my-button').click(function() {
        var params = {
          myFieldValue: $('#my-field').val()
        };

        $.ajax({
          type: 'post',
          url: '" . plugin_dir_url( __FILE__ ) . "process.php',
          data: params,
          success: function(response) {
            console.log(response);
          }
        });
      });
    </script>
  ";
}

function my_form() { 
  ob_start(); 
  my_form_content();
  return ob_get_clean();
}

What the above code does is pretty straightforward.

I will use the shortcode [my_form_shortcode] in the WordPress text editor and it will show a text field and a button. When the button is clicked it will submit the data to process.php using AJAX.

In process.php I have the following code:

<?php
$myFieldValue = $_POST['myFieldValue']

This is also straightforward. I just assigned the value I have received from the client to a variable.

This works just fine but the thing is this is not the WordPress way. The process.php file acts as a stand-alone PHP script where I can't use any WordPress hooks and functions such as wp_mail().

So I know this works, but it is wrong, what is the proper way of doing this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.