I am developing a booking plugin and I need help.
My aim is to get data to and from a database from the WordPress admin menu (I created a custom menu page for it). Now I don’t know how the form should be submitted to a PHP script in WordPress environment.
<!-- HTML FORM -->
<form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
<input type="text" name="reservation_capacity" placeholder="Reservation Capacity" />
<input type="button" name="Add Table" value="Add New Table" />
</form>
I would also need help as to how the plugin would create a form on the website and get data from their as well!
1 Answer
The details of processing form data is specific to PHP therefore I will not go into it. The WordPress-specific part is that you want your code to be run on the ‘init’ event in order to have access to WordPress functions and globals (such as the users permissions).
<?php add_action('init', function(){
$reservation_capacity = sanitize_text_field( $_POST['reservation_capacity'] );
update_user_meta( get_current_user_id(), 'reservation_capacity', $reservation_capacity );
}); ?>
This is just an example where you save the form value to the users meta database (that you probably wouldn’t use in real life).
sanitize_text_field is one of many WP specific functions to sanitize input values. get_current_user_id becomes available after init if a user is logged-in.
More on the topic:
- Validating Sanitizing and Escaping User Data
- Data Validation
- Validating, Sanitizing, and Escaping
- Data Sanitization and Validation With WordPress