Gutenberg/WP - Title field required

Viewed 189

I cannot make the title field (of the post) required before to publish a post with Gutenberg interface.

I try with this function but that don't work. Those functions are not adapted for Gutenberg I think.

function force_post_title_init() {
    wp_enqueue_script('jquery');
}

function force_post_title() {
    echo "<script type='text/javascript'>";
    echo "
        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;
              }
          });
        ";
    echo "</script>";
}

add_action('admin_init', 'force_post_title_init');
add_action('edit_form_advanced', 'force_post_title');
add_action('edit_page_form', 'force_post_title');

Do you have any idea please ?

1 Answers

i am quite confused about what you are trying to do. Post Titles are always required by default, and a page cannot be save without them.

Also - you should not include JS like this. FIrst of all, it is a horrible practice, second of all, it is insanely annoying for you to edit. Include the JS-file with https://developer.wordpress.org/reference/functions/wp_enqueue_script/ instead. Also don't call it "JQuery", because that is confusing. (i assume that you are loading the JQuery library)

So your JS file should be included something like this:

function my_load_scripts($hook) {
    wp_enqueue_script( 'custom_js', 'filepath/custom.js', __FILE__ ), array() );
 
}
add_action('wp_enqueue_scripts', 'my_load_scripts');
Related