当我需要保存“问题”的解决方案时,我创建了一个Ajax函数来验证字段,并进行了一些小的JQuery攻击:
首先,我们添加JavaScript来捕获提交/发布事件,并使用它在实际提交之前提交我们自己的ajax函数
add_action(\'wp_print_scripts\',\'my_publish_admin_hook\');
function my_publish_admin_hook(){
if (is_admin()){
?>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function() {
jQuery(\'#post\').submit(function() {
var form_data = jQuery(\'#post\').serializeArray();
form_data = jQuery.param(form_data);
var data = {
action: \'my_pre_submit_validation\',
security: \'<?php echo wp_create_nonce( \'pre_publish_validation\' ); ?>\',
form_data: form_data
};
jQuery.post(ajaxurl, data, function(response) {
if (response.indexOf(\'True\') > -1 || response.indexOf(\'true\') > -1 || response = true || response) {
jQuery(\'#ajax-loading\').hide();
jQuery(\'#publish\').removeClass(\'button-primary-disabled\');
return true;
}else{
alert("please correct the following errors: " + response);
jQuery(\'#ajax-loading\').hide();
jQuery(\'#publish\').removeClass(\'button-primary-disabled\');
return false;
}
});
return false;
});
});
</script>
<?php
}
}
然后创建函数进行实际验证:
add_action(\'wp_ajax_my_pre_submit_validation\', \'pre_submit_validation\');
function pre_submit_validation(){
//simple Security check
check_ajax_referer( \'pre_publish_validation\', \'security\' );
//do your validation here
//all of the form fields are in $_POST[\'form_data\'] array
//and return true to submit: echo \'true\'; die();
//or your error message: echo \'bal bla bla\'; die();
}
您可以随时对其进行一些更改,以便在客户端进行验证,但我更喜欢在服务器端进行验证。