WordPress-验证元并在古腾堡返回错误消息



以前我做过这个:

function my_save_post($post_id, $post, $update)
{
$errors = new WP_Error('my_errors', 'Something wrong:');
// if having error
$errors->add('my_errors', 'some error message');
//...
//...
//...
if (count($errors->get_error_messages()) > 1) {
global $wpdb;
// set the status of the post to **pending** as its metas has some errors.
$wpdb->update($wpdb->posts, array('post_status' => 'pending'), array('ID' => $post->ID));
set_transient('my_errors', $errors, 10);
} else {
// publish the post and update the metas
}
}
add_action('save_post', 'my_save_post', 10, 3);

function my_notices()
{
if ($errors = get_transient('my_errors')): ?>
<div class="error">
<?php foreach ($errors->get_error_messages() as $error): ?>
<p><?php esc_html_e($error) ?></p>
<?php endforeach; ?>
</div><?php
delete_transient('my_errors');
endif;
}
add_action('admin_notices', 'my_notices');

但现在我不知道如何实现它来验证数据,如果有任何错误,请取消发布帖子,因为它有错误,然后在Gutenberg中返回一些错误消息。

这个问题很宽泛。您无法通过PHP操作Gutenberg。您必须使用Javascript(ES6(、React和Redux的WordPress版本,并熟悉块编辑器API。最好的起点是块编辑器手册。对于简单的用例,您不必了解太多React或Redux,但对于更复杂的用例,这是必要的,至少根据我的经验。关于将帖子状态设置为";"待定";,你应该通过WordPress REST API找到如何做到这一点,然后如果你想在用户决定保存帖子之前使用editEntityRecord('postType', 'post', { appropriate rest updates in form field:value }saveEditedEntityRecord。对于Gutenberg中的通知,你应该使用notices组件。您没有提供数据验证代码,但无论是什么,它都应该用Javascript编写,如果需要,您可以使用getEntityRecord或更多专用的类似函数通过REST获取数据,以从帖子中获取数据。EDIT:我认为editPost操作应该是将post属性更改为挂起的操作,但我不确定,因为我从未使用过它。毕竟,这些专门的操作最终都决定编辑EntityRecord。

最新更新