Jun 23, 2015

Require Post Title for Custom Post Type

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:

// Load admin scripts & styles
function km_load_admin_scripts( $hook ) {
	// If the post we're editing isn't a project_summary type, exit this function.
	if ( 'project_summary' !== get_post_type() ) {
		return;
	}

	// If we're creating/updating the post, exit this function.
	if ( $hook == 'post-new.php' || $hook == 'post.php' ) {
		return;
	}

	// Enqueue JS.
	wp_enqueue_script( 'admin_scripts', get_template_directory_uri() . 'assets/js/km_dashboard_admin.js', array( 'jquery' ) );
}
add_action( 'admin_enqueue_scripts', 'km_load_admin_scripts' );

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:

( function ( $ ) {
	$( document ).ready( function () {

		//Require post title when adding/editing Project Summaries
		$( 'body' ).on( 'submit.edit-post', '#post', function () {

			// If the title isn't set
			if ( $( "#title" ).val().replace( / /g, '' ).length === 0 ) {

				// Show the alert
				window.alert( 'A title is required.' );

				// Hide the spinner
				$( '#major-publishing-actions .spinner' ).hide();

				// The buttons get "disabled" added to them on submit. Remove that class.
				$( '#major-publishing-actions' ).find( ':button, :submit, a.submitdelete, #post-preview' ).removeClass( 'disabled' );

				// Focus on the title field.
				$( "#title" ).focus();

				return false;
			}
		});
	});
}( jQuery ) );

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:

// The list of post types that we want to require post titles for
$post_types = array( 'post', 'page', 'event', 'project' );

// If the current post is not one of the chosen post types, exit this function
if ( ! in_array( $post->post_type, $post_types ) ) {
	return;
}