Skip to content

Instantly share code, notes, and snippets.

@UmeshSingla
Created September 15, 2017 08:20
Show Gist options
  • Save UmeshSingla/1d05dbf3d3916e8ccf2da1cffda2f2f2 to your computer and use it in GitHub Desktop.
Save UmeshSingla/1d05dbf3d3916e8ccf2da1cffda2f2f2 to your computer and use it in GitHub Desktop.
WordPress Post: Check for empty title before publishing and show a warning. Post is saved as draft if the title is empty.
<?php
//WordPress Stack Exchange Link: https://wordpress.stackexchange.com/questions/279947/check-post-on-publish-for-blank-title/279994#279994
//Make sure to upvote if you find it helpful.
/**
* Checks for empty post title, if empty sets the post status to draft
*
* @param $data
* @param $postarr
*
* @return array
*/
function wse_279994_check_post_title( $data, $postarr ) {
if ( is_array( $data ) && 'publish' == $data['post_status'] && empty( $data['post_title'] ) ) {
$data['post_status'] = 'draft';
update_option( 'wse_279994_post_error', 'empty_title' );
}
return $data;
}
add_filter( 'wp_insert_post_data', 'wse_279994_check_post_title', 10, 2 );
/**
* If the post title was empty, do not show post published message
*/
add_filter( 'post_updated_messages', 'wse_279994_remove_all_messages' );
function wse_279994_remove_all_messages( $messages ) {
if ( get_option( 'wse_279994_post_error' ) ) {
return array();
} else {
return $messages;
}
}
/**
* Show admin notice for empty post title
*/
add_action( 'admin_notices', 'wse_279994_show_error' );
function wse_279994_show_error() {
$screen = get_current_screen();
if ( $screen->id != 'post' ) {
return;
}
if ( ! get_option( 'wse_279994_post_error' ) ) {
return;
}
echo '<div class="error"><p>' . esc_html__( "You need to enter a Post Title in order to publish it.", "wse" ) . '</p></div>';
delete_option( 'wse_279994_post_error' );
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment