我正在开发前端表单插件,在使用验证错误消息时遇到问题WP_Error
. 我花了几个小时才找到问题,但还是不知道。
下面的代码确实有效,但我真的不认为我应该使用return false;
在内容验证错误消息下方。
/*
** Process data from front end form
http://codex.wordpress.org/Function_Reference/wp_insert_post
*/
function write_here_add_new_post() {
if( \'POST\' == $_SERVER[\'REQUEST_METHOD\'] && !empty( $_POST[\'action\'] ) && $_POST[\'action\'] == "write_here_new_post") {
$title = wp_strip_all_tags($_POST[\'title\']);
$content = $_POST[\'content\'];
$postdate = $_POST[\'date\'];
$gmtpostdate = $_POST[\'date\'];
$tags = $_POST[\'post_tags\'];
$cat = $_POST[\'cat\'];
// Server side validation
if ($title == \'\') {
write_here_errors()->add(\'title_not_vaild\', __(\'Title not valid\'));
}
if ($content == \'\') {
write_here_errors()->add(\'content_not_vaild\', __(\'Content not valid\'));
return false;
}
if (!$postdate) {
$postdate = date(\'Y-m-d H:i:s\');
$gmtpostdate = gmdate(\'Y-m-d H:i:s\');
}
// Add the content of the form to $post as an array
$new_post = array(
\'post_title\' => $title,
\'post_content\' => $content,
\'post_category\' => array($cat), // Default empty.
\'tags_input\' => array($tags), // Default empty.
\'post_status\' => \'publish\', // Choose: publish, preview, future, draft, etc. Default \'draft\'.
\'post_date\' => $postdate, // The time post was made.
\'post_date_gmt\' => $gmtpostdate // The time post was made, in GMT.
);
//save the new post and return its ID
$post_id = wp_insert_post($new_post);
// This will redirect you to the newly created post (Using GUID)
$post = get_post($post_id);
wp_redirect($post->guid);
exit();
}
}
add_action(\'init\', \'write_here_add_new_post\');
// used for tracking error messages
function write_here_errors(){
static $wp_error; // Will hold global variable safely
return isset($wp_error) ? $wp_error : ($wp_error = new WP_Error(null, null, null));
}
// displays error messages from form submissions
function write_here_show_error_messages() {
if($codes = write_here_errors()->get_error_codes()) {
echo \'<div class="form-error">\';
// Loop error codes and display errors
foreach($codes as $code){
$message = write_here_errors()->get_error_message($code);
echo \'<span class="error"><strong>\' . __(\'Error\') . \'</strong>: \' . $message . \'</span><br/>\';
}
echo \'</div>\';
}
}
谁能告诉我哪里做错了什么?要获取验证错误消息,请使用
WP_Error
? 非常感谢。