Gutenberg-标题字段为必填字段

时间:2020-05-27 作者:Jandon

我想让title 中需要的字段Gutenberg 编辑器界面。

我发现可以使用的PHP函数Classic 编辑器界面,但不带Gutenberg.

我试图添加required 属性,但我仍然可以验证帖子的发布。

<?php  
function wp_required_title_field() {
    ?>
    <script type="text/javascript">
        jQuery(window).load(function() {
            jQuery(\'.editor-post-title textarea\').prop(\'required\',true);
        });
    </script>
    <?php
}

add_action (\'in_admin_footer\' , \'wp_required_title_field\');
?>
我也尝试了另一种方法:

<?php  
function force_post_title() {
    ?>
    <script type="text/javascript">
        jQuery(window).load(function() {
            jQuery(\'.editor-post-publish-button__button\').click(function(){
              var testervar = jQuery(\'.editor-post-title\').find(\'.editor-post-title__input\');
              if (testervar.val().length < 1) {
                  jQuery(\'.editor-post-title\').css(\'border\', \'1px solid red\');
                  $( \'.editor-post-title\' ).after(\'<label>Post title is required</label>\'); // Make it red according your requirement
                  return false;
              }
          });
        });
    </script>
    <?php
}

add_action(\'edit_form_advanced\', \'force_post_title\');
add_action(\'edit_page_form\', \'force_post_title\');
?>
你有什么想法吗?

1 个回复
最合适的回答,由SO网友:Welcher 整理而成

你可以使用PluginPrePublishPanel 检查标题,如果标题为空,则锁定发布。查看此处公认的答案,以获取锁定帖子的示例-Add pre-publish conditions to the block editor

对于您的示例,您可以修改检查部分,如下所示:

const { registerPlugin } = wp.plugins;
const { PluginPrePublishPanel } = wp.editPost;
const { select, dispatch } = wp.data;
const { count } = wp.wordcount;
const { serialize } = wp.blocks;
const { PanelBody } = wp.components;

const PrePublishCheckList = () => {
    let lockPost = false;
    let message = \'\';

    // Get title 
    const postTitle = select( \'core/editor\' ).getEditedPostAttribute( \'title\' );
    if ( postTitle === \'\' ) {
        lockPost = true;
        message = \'Post Title is required!\';
    }


    // Do we need to lock the post?
    if ( lockPost === true ) {
         dispatch( \'core/editor\' ).lockPostSaving();
    } else {
         dispatch( \'core/editor\' ).unlockPostSaving();
    }
    return (
        <PluginPrePublishPanel title={ \'Publish Checklist\' }>
            <p>{message}</p>
        </PluginPrePublishPanel>
    )
};

registerPlugin( \'pre-publish-checklist\', { render: PrePublishCheckList } 
希望这有帮助!