Require a Title Before Publishing
Prevents posts and pages from being published or scheduled without a title, avoiding "(no title)" entries in menus, feeds, search results and social shares.
Opens WPIDE on
Code
// Post types that need a title.
$wpide_title_required_types = array( 'post', 'page' );
foreach ( $wpide_title_required_types as $wpide_type ) {
add_filter( "rest_pre_insert_{$wpide_type}", function ( $prepared, $request ) {
$status = $request->get_param( 'status' ) ? $request->get_param( 'status' ) : get_post_status( (int) ( $prepared->ID ?? 0 ) );
if ( ! in_array( $status, array( 'publish', 'future' ), true ) ) {
return $prepared;
}
$title = null !== $request->get_param( 'title' ) ? $request->get_param( 'title' ) : get_post_field( 'post_title', (int) ( $prepared->ID ?? 0 ), 'raw' );
$title = is_array( $title ) ? ( $title['raw'] ?? '' ) : (string) $title;
return '' === trim( wp_strip_all_tags( $title ) )
? new WP_Error( 'wpide_title_required', 'Please add a title before publishing.', array( 'status' => 400 ) )
: $prepared;
}, 10, 2 );
}
// Classic editor and other code paths.
add_filter( 'wp_insert_post_data', function ( $data ) use ( $wpide_title_required_types ) {
if ( in_array( $data['post_type'], $wpide_title_required_types, true ) && in_array( $data['post_status'], array( 'publish', 'future' ), true ) && '' === trim( wp_strip_all_tags( wp_unslash( $data['post_title'] ) ) ) && ! wp_is_serving_rest_request() ) {
$data['post_status'] = 'draft';
}
return $data;
} );
Notes
Drafts without a title can still be saved; add other post types to $wpide_title_required_types.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.