Reputation: 6802
I'm creating an options page in WordPress admin interface. How can I run a PHP function before a submit is made?
My HTML:
<div class="wrap">
<h2>Author</h2>
<form method="post" action="options.php">
<?php settings_fields('author_option_group'); ?>
<h4>Author Settings</h4>
<label for="author">Author: </label>
<input type="text" id="author" name="author" value="<?php echo get_option('author'); ?>" />
<?php submit_button(); ?>
</form>
The submit_button()
above is a wordpress function that generates a submit button that saves the input field to the wp options table in the database. I would like to run a function before the submit is run. The function will do some custom validation etc and maybe throw an error and not run the submit if certain conditions are met.
Regardless of what that function will do, how can I supply a function to be run, which determines if the submit will go through or not?
Upvotes: 2
Views: 3841
Reputation: 594
If you want to validate form in client side so you have to use javascript, if you are using jquery it will be like this.
$(document).ready(function(){
$('form').on('submit',function(){
// validation
// if everything is ok return true else return false and show errors
});
})
If you want do validation in server side you have to run your validation before showing form.
You can use wp hook, you can check validation in your options.php
or you can check it in functions.php
. With hook it will look like .
<?php do_action('before_form_rendered') ?>
<form method="post" action="options.php">
<?php settings_fields('author_option_group'); ?>
<h4>Author Settings</h4>
<label for="author">Author: </label>
<input type="text" id="author" name="author" value="<?php echo get_option('author'); ?>" />
<?php submit_button(); ?>
</form>
and add this code in your functions.php
add_action('before_form_rendered','validate_author_form');
function validate_author_form(){
if(isset($_POST['author']) && !empty($_POST['author'])){
echo 'form has been submited';
}else{
echo 'please insert author name';
}
}
Also you can implement your form by ajax.
JS side
$('form').on('submit', function(){
$.post('http://yoursite/wp-admin/admin-ajax.php', {
action: 'custom_form',
data : $(this).serializeArray()
},function(response){
// handle server response here
console.log(response);
});
return false;
});
php code add in your functions.php
add_action( 'wp_ajax_custom_form', 'custom_form_handler' );
add_action( 'wp_ajax_nopriv_custom_form', 'custom_form_handler' );
// validation goes here
function custom_form_handler(){
echo "<pre>";
var_dump($_POST);
echo "</pre>";
exit;
}
Best Regards, Davit.
Upvotes: 3
Reputation: 11
i think 2 way can help you. 1. change the input type "submit" the file is wp-admin\includes\template.php (unction get_submit_button) 2.use preventDefault
onsubmit{
//docheck
if(checked){
//nothing do
}else{
alert(wrong);
e.preventDefault
}
}
but preventDefault IE not support
Upvotes: 1