Sometimes people get a bit carried away, typing in massively long strings into the post title. This is often just after they have learnt that the WordPress slug creates a pretty permalink that is good for SEO. The idea that focussing keywords is stronger than diluting them with everything under the sun seems to take a little while longer to sink in.
You can pop this little snippet in your functions.php and it will restrict the character count, word count and also automatically re-set the post status back to draft.
Restrict Post Title Length
add_action( 'publish_post', 'tcb_restrict_post_title', 11, 2 );
function tcb_restrict_post_title( $post_id, $post ){
$title = $post->post_title;
$MAX_WORDS = 8;
$MAX_CHARS = 50;
$err_mess = '';
$set_to_draft = 1;
if( $MAX_WORDS && str_word_count( $title ) > $MAX_WORDS )
$err_mess .= " Your post title exceeds maximum word count ({$MAX_WORDS}).";
if( $MAX_CHARS && strlen( $title ) > $MAX_CHARS )
$err_mess .= " Your post title exceeds the maximum character count({$MAX_CHARS}).";
if( $err_mess ) :
if( $set_to_draft )
wp_update_post( array( 'ID'=>$post_id, 'post_status'=>'draft' ) );
wp_die( __($err_mess, 'tcb') );
endif;
return $post_id;
}
You can toggle setting the draft status off and on easily with $set_to_draft, and if you want to be more or less restrictive on your word and characters counts, just change the numbers in $MAX_WORDS and $MAX_CHARS.
What does wp_die() cause to be displayed in that situation?
It will display whatever is in the $err_mess variable.
Nice code.