Reputation: 1
I have made a page in Wordpress with a form like this:
<form id="contact" action="<?= $_SERVER['PHP_SELF'];?>" method="post">
<h3>Beschikbaarheid</h3>
<h4>Geef uw beschikbare werktijden door.</h4>
<fieldset>
<input placeholder="Uw naam" type="text" name="name" value="<?= $name ?>" tabindex="1">
<span class="error"><?= $name_error ?></span>
</fieldset>
<fieldset>
<input placeholder="Uw Emailadres" type="text" name="email" value="<?= $email ?>" tabindex="2">
<span class="error"><?= $email_error ?></span>
</fieldset>
I have put the functions for this form in functions.php but it doesn;t work. What is the proper way to make a functioning form?
Upvotes: 0
Views: 190
Reputation: 653
Best way for handlig forms - use admin-post.php
and don`t forget valid and escaping data.
Good tutorial here
Change your form action to <?php echo admin_url('admin-post.php'); ?>
. Create field with name action:
<input name="action" value="my_action">
Create hooks in your functions.php file.
add_action('admin_post_my_action', 'form_handler');
add_action('admin_post_nopriv_my_action', 'form_handler');
function form_handler(){
// handle your form. Use $_POST here
}
And do not forget use nonce
.
Upvotes: 1
Reputation: 623
[Updated]
Set your form action as below, so that it submits the data to this page and doesn't redirect to another page. And you have to change the input field name
attribute. Not sure why name
as the value of name
attribute isn't working, otherwise everything works fine. I've tested on my local dev environment.
<form id="contact" method="post" action="<?php the_permalink(); ?>">
Sorry, I didn't know that there is a request handler. Here are the details https://codex.wordpress.org/Plugin_API/Action_Reference/admin_post_(action) and here is the modified tag
<form id="contact" method="post" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
Upvotes: 0