In this post, I’ll outline how to make the post title field required for a custom post type in WordPress. By default, if a user leaves the title field blank, WordPress will still allow the post to be published or updated. What we want to do is prevent the custom post type from being published/updated until it has a valid title, and let the user know they need to enter one.

First we need to enqueue our javascript file by adding the code below to the functions.php file:

Just be sure to change the assets/js/<filename> to the path where you’ll put the javascript file below on your web server, and change ‘post_summary’ to the name of your custom post type.

Next, create a new file named km_dashboard_admin.js in a text editor and paste in this code:

If a title hasn’t been entered, we’re showing the user a popup box that says “A title is required.” and then putting the focus on the title field so they can enter one. Upload that javascript file to the path you specified when you enqueued it, above.

That’s it! If you want to require post titles for multiple post types, you can change the km_load_admin_scripts() function to contain the snippet below, with your post types in the list:

8 comments

  1. Jonny Bravo March 8, 2016 at 7:28 am

    Reply

    Hey — nice article, thanks. Just to say I think you meant !in_array()

    • Kellen Mace March 8, 2016 at 8:06 am

      Reply

      Hey- thanks for catching that! I just updated it. Glad you found the post helpful 🙂

  2. jomko March 24, 2016 at 10:28 am

    Reply

    Thank you!

  3. Hardik August 6, 2016 at 6:46 am

    Reply

    I have total 3 checkbox, one should be checked before publish custom post type. How to make custom checkbox field mandatory?

  4. Bhagwad Jal Park August 22, 2016 at 7:28 pm

    Reply

    Hi Kellen. Nice article! However, do you think there’s a way to display a message to the user without having to include a Javascript file?

    For example, this website shows some code using the “post_updated_messages” action to display a message to the user if the content doesn’t have a certain minimum number of words: https://www.webhostinghero.com/how-to-set-a-minimum-length-for-wordpress-posts/ .

    I’m sure it could be modified to check for a blank title instead of the content length right?

    • Kellen Mace March 24, 2017 at 9:25 am

      Reply

      No, using the post_updated_messages hook to display an admin message wouldn’t be possible, since that hook only fires after a post has been saved. Including the JS file is necessary because it prevents the create/edit post screen form from being submitted and the post from being saved in the first place.

  5. Rob August 24, 2016 at 10:24 am

    Reply

    Super helpful, thanks for writing this.

Leave a reply

Your email address will not be published. Required fields are marked *