好的,这里有几篇关于前端投递表单的帖子。我把它们都读了,这让我明白了我的意思。现在,我遇到的每一个表单都有某种形式的验证,它似乎可以检查您想要设置为必需的字段的值。我试过了,但什么都没用。我只是无法设置任何必填字段。表单的其他方面都很完美。但我希望强制执行我的必填字段(适当错误消息的奖励)。
我试着在google上四处看看,我真的不认为JS是我想要使用的。以及任何其他我似乎也无法进行的php验证。我敢肯定,我把它们都弄错了。
以下是我所拥有的:http://pastebin.com/rw4c6jZQ (应验证完整的模板行9-19)
模板的“收件人”处的我的处理脚本:
<?php
if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && !empty( $_POST[\'action\'] ) && $_POST[\'action\'] == "new_post") {
// Do some minor form validation to make sure there is content
if (isset ($_POST[\'title\'])) {
$title = $_POST[\'title\'];
} else {
echo \'Please enter the wine name\';
}
if (isset ($_POST[\'description\'])) {
$description = $_POST[\'description\'];
} else {
echo \'Please enter some notes\';
}
$tags = $_POST[\'post_tags\'];
$winerating = $_POST[\'winerating\'];
// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
\'post_title\' => $title,
\'post_content\' => $description,
\'post_category\' => array($_POST[\'cat\']), // Usable for custom taxonomies too
\'tags_input\' => array($tags),
\'post_status\' => \'publish\', // Choose: publish, preview, future, draft, etc.
\'post_type\' => \'post\', //\'post\',page\' or use a custom post type if you want to
\'winerating\' => $winerating
);
//SAVE THE POST
$pid = wp_insert_post($new_post);
//KEEPS OUR COMMA SEPARATED TAGS AS INDIVIDUAL
wp_set_post_tags($pid, $_POST[\'post_tags\']);
//REDIRECT TO THE NEW POST ON SAVE
$link = get_permalink( $pid );
wp_redirect( $link );
//ADD OUR CUSTOM FIELDS
add_post_meta($pid, \'rating\', $winerating, true);
//INSERT OUR MEDIA ATTACHMENTS
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$pid);
// $newupload returns the attachment id of the file that
// was just uploaded. Do whatever you want with that now.
}
} // END THE IF STATEMENT FOR FILES
} // END THE IF STATEMENT THAT STARTED THE WHOLE FORM
//POST THE POST YO
do_action(\'wp_insert_post\', \'wp_insert_post\');
表单和其他所有内容都可以在pastebin中查看,以便在上下文中查看。非常感谢!
最合适的回答,由SO网友:Matthew Muro 整理而成
进行表单验证的最佳方法是结合使用JavaScript和PHP。
之所以要执行JavaScript验证,是为了让用户有机会在不提交表单的情况下更正错误。此外,它将阻止任何偶然的错误。您还需要确保在关闭JavaScript的情况下在后端进行验证。
无论哪种方式,清理数据都应该是此过程的一部分。使用以下任一WordPress功能可帮助您:Data Validation.
对于JavaScript验证,我建议jQuery Validation plugin. 它非常容易实现和定制。
对于PHP验证,您可以尝试添加此项以检查空值:$_POST[\'title\'] != \'\'