我把它砍掉了。这是我对一个简单问题的最丑陋的解决方案。我对这件事不是很满意,但必须这样做。
在本例中,我将使用一个名为book
我们要验证一个名为ISBN
. 此解决方案使用PHP Session
和header redirect
.
我们开始吧。。。
Step 1 - Data Validation
使用过滤器挂钩进行数据验证
wp_insert_post_data
, 就在数据插入数据库之前。如果无效,我们将设置一个无效标志,并在将数据插入数据库之前重定向用户。
function pre_insert_book($data, $postarr)
{
if ($data[\'post_type\'] === "book" && in_array($data[\'post_status\'], [\'publish\', \'draft\', \'pending\']) && !empty($_POST) && isset($_POST[\'ISBN\'])) {
$ISBN = sanitize_text_field($_POST[\'ISBN\']);
if (empty($ISBN)) {
session_start();
$_SESSION[\'POST\'] = $_POST;
header("Location: " . admin_url(\'post-new.php?post_type=book&invalid=empty_ISBN\'));
exit;
} elseif (!validade_ISBN($ISBN)) {
session_start();
$_SESSION[\'POST\'] = $_POST;
header("Location: " . admin_url(\'post-new.php?post_type=book&invalid=invalid_ISBN\'));
exit;
}
}
return $data;
}
add_filter(\'wp_insert_post_data\', \'pre_insert_book\', 10, 2);
Step 2 - Display error notice
如果抛出无效标志,我们会向用户显示一个错误。我们还保留了书名,以便在提交表单时不会丢失数据。我相信这可以在其他地方完成。
function check_insert_book_error_notices()
{
global $current_screen, $post;
if ($current_screen->parent_file === "edit.php?post_type=book" && isset($_GET[\'invalid\'])) {
session_start();
// We want to keep the book title like so (and other values if necessary)
if (isset($_SESSION["POST"]) && isset($_SESSION["POST"][\'post_title\']))
$post->post_title = $_SESSION["POST"][\'post_title\'];
if (esc_attr($_GET[\'invalid\']) === "empty_ISBN") {
echo \'<div class="error"><p>ISBN number cant be empty</p></div>\';
} elseif (esc_attr($_GET[\'invalid\']) === "invalid_ISBN") {
echo \'<div class="error"><p>ISBN is not valid</p></div>\';
}
}
}
add_action(\'admin_notices\', \'check_insert_book_error_notices\');
Step 3 - Dealing with the ISBN form field and Session
当出现错误时,返回到空表单并不有趣,让会话保持打开状态也不是一种好的做法。所以我们在这里处理这个问题。
function load_custom_book_meta_boxes()
{
add_meta_box(\'isbn-form\', \'Book data\', array($this, \'custom_form_for_book_post_type\'), \'book\', \'normal\', \'high\');
}
add_action(\'add_meta_boxes\', \'load_custom_book_meta_boxes\');
function custom_form_for_book_post_type($post)
{
session_start();
$ISBN_previous_value = "";
if (isset($_SESSION["POST"]) && isset($_SESSION["POST"][\'ISBN\']))
$ISBN_previous_value = sanitize_text_field($_SESSION["POST"][\'ISBN\']);
session_destroy();
ob_start(); ?>
<div id="isbn-form-container">
<form class="isbn-form" method="post" action="">
<table>
<tr class="isbn-row">
<td><label for="ISBN">Book ISBN</label></td>
<td><input type="number" id="ISBN" class="required" name="ISBN" value="<?php echo $ISBN_previous_value; ?>" autocomplete="off" required></td>
</tr>
</table>
</form>
</div>
<?php ob_end_flush();
}
一切似乎都很顺利;我只做了一点测试,稍后会回来做更多的测试。
希望它能帮助一些想要类似东西的人。