4

I want to make post titles mandatory in the post editor without Javascript or PHP validation, I'd like something really simple like adding the HTML "required" attribute to the post title input element.

I see there is "edit_form_top" and "edit_form_after_title" but those hook juste before and just after the title input.

Is there any way to actually change the HTML of the post title field ?

2

There is no hook to change the HTML of the input (only the enter_title_here filter to change the placeholder text). You could pull this off easily with jQuery, though. Try this in your functionality plugin or theme's functions.php file:

// Add to the new post screen for any post type
add_action( 'admin_footer-post-new.php', 'wpse_add_required_attr_to_title_field' );

// Add to the post edit screen for any post type
add_action( 'admin_footer-post.php', 'wpse_add_required_attr_to_title_field' );

function wpse_add_required_attr_to_title_field() {
    ?>
    <script>
        jQuery(document).ready(function($){
            $('input[name=post_title]').prop('required',true);
        });
    </script>
    <?php
}

I should note, however, not knowing what your user base for this site's administration looks like, that the prevention of submitting a form based solely on the required attribute isn't implemented exactly the same across the board, so if this matters for your use case, you might want to look at an implementation that forces it's own alert, like for example in the Force Post Title plugin.

  • I ended up going the jQuery way with a WP style error message, as the required attribute displays different tooltips depending on the browser. – mike23 Oct 24 '16 at 8:33
1

As brianjohnhanna points out there is no hook to change the HTML of the title field, so the closest possible answer is to do jQuery validation.

Here's what I ended up doing, create a plugin with :

function wpse_242302_mandatory_title( $hook ) {

    global $post;

    if ( $hook == 'post-new.php' || $hook == 'post.php' ) {

        wp_enqueue_script( 'mandatory-title', plugins_url( 'mandatory-title.js', __FILE__ ), array( 'jquery' ) );

    }
}
add_action( 'admin_enqueue_scripts', 'wpse_242302_mandatory_title', 20, 1 );

and the javascript :

$(document).ready(function() {

    $('#post').submit(function(){

        if( !$('input[name=post_title]').val() ) {

            $( '.wrap > h1').after('<div id="message" class="error"><p>Please enter a title.</p></div>' );

            return false;

        }

    });

});

Instead of adding the "required" attribute it displays a default Wordpress error message, I thought this integrated better with the admin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.