【问题标题】:WordPress - Validate metas and return error message in GutenbergWordPress - 在 Gutenberg 中验证元数据并返回错误消息
【发布时间】:2022-01-25 19:42:03
【问题描述】:

以前我是这样做的:

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 wordpress wordpress-gutenberg


    【解决方案1】:

    这个问题非常广泛。您不能通过 PHP 操作古腾堡。 您必须使用 Javascript (ES6)、WordPress 版本的 React 和 Redux 并熟悉 Block editor API。最好的起点是Block Editor Handbook。对于简单的用例,你不必对 React 或 Redux 了解太多,但对于更复杂的用例,至少在我的经验中是必要的。关于将帖子状态设置为“待处理”,您应该找到如何通过 WordPress REST API 执行此操作,然后使用 editEntityRecord('postType', 'post', { appropriate rest updates in form field:value } 并使用 saveEditedEntityRecord 如果您想在用户决定之前保存帖子。对于古腾堡的通知,您应该使用Notices Component。您没有提供数据验证代码,但无论如何,它都应该用 Javascript 编写,您可以使用getEntityRecord 或更专用的类似函数通过 REST 获取数据,以便在需要时从帖子中获取数据。 编辑:我相信editPost 操作应该是将post 属性更改为pending 的操作,但是我不确定,因为我从未使用过它。毕竟这种专门化的动作最后都解析为editEntityRecord。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-20
      • 2015-11-10
      • 1970-01-01
      • 2016-08-06
      • 2011-10-22
      • 2017-08-15
      • 1970-01-01
      相关资源
      最近更新 更多